想讓窗體在桌面上像屏保一樣自動水平往返滑動?只需兩個 Timer 控制 X 座標增減,配合 DesktopLocation 即可輕鬆實現。本文提供完整代碼、擴展思路(垂直、對角、隨機軌跡)以及性能優化建議。
timer1:每 Tick 將 DesktopLocation.X += 1,向右移動timer2:每 Tick 將 DesktopLocation.X -= 1,向左移動using System;
using System.Windows.Forms;
namespace FloatingFormDemo
{
public partial class Form1 : Form
{
private const int LeftBound = 20;
private const int RightBound = 630;
private const int Step = 2; // 像素/幀,越大越快
private const int Interval = 10; // 毫秒/幀,約 100 FPS
public Form1()
{
InitializeComponent();
// 無邊框、置頂、不顯示在任務欄,更像屏保
this.FormBorderStyle = FormBorderStyle.None;
this.TopMost = true;
this.ShowInTaskbar = false;
this.BackColor = Color.Black; // 方便看清邊界
this.TransparencyKey = Color.Black; // 若想透明可設圖片背景色
this.Size = new Size(100, 50); // 小窗體
}
private void Form1_Load(object sender, EventArgs e)
{
// 起始位置:左邊界、螢幕垂直置中
this.DesktopLocation = new Point(LeftBound,
(Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
timer1.Interval = Interval;
timer2.Interval = Interval;
timer1.Tick += Timer1_Tick;
timer2.Tick += Timer2_Tick;
timer1.Start(); // 先向右
}
private void Timer1_Tick(object sender, EventArgs e)
{
int newX = this.DesktopLocation.X + Step;
if (newX >= RightBound)
{
newX = RightBound;
timer1.Stop();
timer2.Start();
}
this.DesktopLocation = new Point(newX, this.DesktopLocation.Y);
}
private void Timer2_Tick(object sender, EventArgs e)
{
int newX = this.DesktopLocation.X - Step;
if (newX <= LeftBound)
{
newX = LeftBound;
timer2.Stop();
timer1.Start();
}
this.DesktopLocation = new Point(newX, this.DesktopLocation.Y);
}
// 點擊窗體任意處停止動畫並關閉
protected override void OnClick(EventArgs e)
{
timer1.Stop();
timer2.Stop();
this.Close();
base.OnClick(e);
}
// 設計器自動生成兩個 Timer
private System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
private System.Windows.Forms.Timer timer2 = new System.Windows.Forms.Timer();
}
}
| 軌跡類型 | 實現要點 |
|---|---|
| 垂直往返 | 修改 Y 座標,X 固定 |
| 對角線往復 | 同時修改 X、Y,邊界判斷用 && |
| 矩形邊框巡航 | 四個 Timer/狀態機:右→下→左→上 |
| 隨機游走 | 單 Timer,每 Tick X += Random(-3,3),邊界反彈 |
| 跟隨滑鼠 | Timer 內 this.DesktopLocation = Cursor.Position 加平滑插值 |
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);Screen.PrimaryScreen.WorkingArea 而非硬編碼邊界。Interval ≥ 10ms,Step ≤ 5px,避免佔用過高。Screen.AllScreens 計算虛擬桌面邊界。FormClosing 釋放 Timer、取消事件訂閱。DoubleAnimation + TranslateTransform,GPU 加速、聲明式、更流暢。user32.dll AnimateWindow 系統級動畫,無需 Timer。/s /p /c 切換全屏/預覽/設置。雙 Timer + DesktopLocation 是 WinForms 實現窗體自動飄動最簡單、最直觀的方案。理解邊界檢測與狀態切換邏輯後,靈活組合即可創造各種趣味動畫。記住優化 DPI、多螢幕、CPU 佔用,才能從「能跑」進化為「好用」。