首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# Timer 元件實戰:讓視窗飄動起來(一)設計思路與關鍵步驟

     編輯:關於C語言

Timer 元件基本認知

  • 命名空間:System.Windows.Forms
  • 特性:不可見元件 (設計時不顯示在視窗上)
  • 功能:啟動後每隔固定間隔 (Interval) 觸發 Tick 事件
  • 屬性極少:Enabled、Interval、Tick 事件

開發環境

  • 作業系統:Windows 2000 Server
  • 開發工具:.NET Framework SDK Beta 2

程式設計核心思路

  1. 初始化位置:Form_Load 設定 DesktopLocation 為螢幕座標 (0, 240)
  2. 雙 Timer 分工:
    • Timer1:控制向右移動 (X + 1),Interval = 10ms
    • Timer2:控制向左移動 (X - 1),Interval = 10ms
  3. 互斥啟用:同一時間僅啟用一個 Timer
  4. 邊界切換:
    • X 達 550 → 停用 Timer1,啟用 Timer2
    • X 達 -150 → 停用 Timer2,啟用 Timer1
  5. 無限循環:兩 Timer 交替啟用,視窗持續來回飄動

關鍵步驟詳細實作

1. 設定視窗初始位置


private void Form1_Load(object sender, EventArgs e)
{
    Point p = new Point(0, 240);  // 螢幕左側、垂直置中約略位置
    this.DesktopLocation = p;
}

DesktopLocation 為視窗左上角在螢幕座標系的位置。

2. 實現向右飄動 (Timer1)


// Interval = 10 (0.01 秒)
private void Timer1_Tick(object sender, EventArgs e)
{
    Point p = new Point(this.DesktopLocation.X + 1, this.DesktopLocation.Y);
    this.DesktopLocation = p;
    
    if (p.X == 550)  // 到達右側邊界
    {
        timer1.Enabled = false;
        timer2.Enabled = true;
    }
}

3. 實現向左飄動 (Timer2)


private void Timer2_Tick(object sender, EventArgs e)
{
    Point p = new Point(this.DesktopLocation.X - 1, this.DesktopLocation.Y);
    this.DesktopLocation = p;
    
    if (p.X == -150)  // 到達左側邊界 (超出螢幕左側形成視覺循環)
    {
        timer1.Enabled = true;
        timer2.Enabled = false;
    }
}

完整程式碼架構預覽


namespace FloatingForm
{
    public class Form1 : Form
    {
        private Timer timer1, timer2;
        private Label label1;
        private Button button1;
        private Container components;
        
        // InitializeComponent: 建構所有控制項、設定 Timer、事件綁定
        // Form1_Load: 設定初始位置
        // Timer1_Tick: 向右移動 + 邊界切換
        // Timer2_Tick: 向左移動 + 邊界切換
        // Button1_Click: timer1.Stop(); timer2.Stop();
    }
}

下篇預告

下一篇將提供完整可編譯執行的 Form1.cs 原始碼、執行效果說明,以及擴充方向建議 (垂直飄動、隨機軌跡、無邊框圖片模式等)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved