using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace FloatingForm
{
public class Form1 : Form
{
private Timer timer1;
private Timer timer2;
private Label label1;
private Button button1;
private Container components;
public Form1()
{
InitializeComponent();
}
protected override void Dispose(bool disposing)
{
if (disposing && components != null)
components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
components = new Container();
timer1 = new Timer(components);
timer2 = new Timer(components);
label1 = new Label();
button1 = new Button();
this.SuspendLayout();
// Timer1: 向右移動 (每 10ms)
timer1.Enabled = true;
timer1.Interval = 10;
timer1.Tick += Timer1_Tick;
// Timer2: 向左移動 (每 10ms,初始停用)
timer2.Enabled = false;
timer2.Interval = 10;
timer2.Tick += Timer2_Tick;
// Button: 停止飄動
button1.Font = new Font("新細明體", 10);
button1.Location = new Point(1, 8);
button1.Name = "button1";
button1.Size = new Size(80, 25);
button1.TabIndex = 0;
button1.Text = "停止飄動";
button1.Click += Button1_Click;
// Label: 顯示文字
label1.Font = new Font("新細明體", 22F, FontStyle.Bold);
label1.Location = new Point(8, 38);
label1.Name = "label1";
label1.Size = new Size(344, 40);
label1.TabIndex = 1;
label1.Text = "用 Visual C# 做的飄動視窗!";
// Form 設定
this.AutoScaleBaseSize = new Size(5, 13);
this.ClientSize = new Size(352, 70);
this.Controls.Add(label1);
this.Controls.Add(button1);
this.Name = "Form1";
this.Text = "用 Visual C# 做的飄動視窗!";
this.Load += Form1_Load;
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
// 設定初始位置 (螢幕座標 0, 240)
private void Form1_Load(object sender, EventArgs e)
{
this.DesktopLocation = new Point(0, 240);
}
// 向右移動:X + 1,到達 550 切換 Timer2
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;
}
}
// 向左移動:X - 1,到達 -150 切換 Timer1
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;
}
}
// 停止所有 Timer
private void Button1_Click(object sender, EventArgs e)
{
timer1.Stop();
timer2.Stop();
}
}
}
| 技術點 | 實作細節 |
|---|---|
| Timer 元件特性 | 不可見元件、命名空間 System.Windows.Forms、固定間隔觸發 Tick 事件 |
| 雙 Timer 交替 | timer1 向右、timer2 向左,同一時間只啟用一個 |
| 視窗位置控制 | Form.DesktopLocation 屬性 (螢幕座標),Point 結構設定 X/Y |
| 邊界檢測切換 | X == 550 切向左,X == -150 切向右 |
| 資源釋放 | Dispose 模式正確釋放 components 容器 |
Random 讓方向、速度、邊界隨機變化FormBorderStyle = None,填入精美圖片當背景Screen.PrimaryScreen.WorkingArea 計算真實邊界Timer 元件雖屬性事件極少,但善用可產生意想不到效果。本範例展示雙 Timer 交替控制視窗位置,實現水平來回飄動。掌握 DesktopLocation、Timer.Interval、Tick 事件 三要素,即可實作各類定時動畫與輪詢邏輯。