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

C# WinForms 實現會「飄動」的窗體—— 定時器動畫完整教程

     編輯:關於C#

想讓窗體在桌面上像屏保一樣自動水平往返滑動?只需兩個 Timer 控制 X 座標增減,配合 DesktopLocation 即可輕鬆實現。本文提供完整代碼、擴展思路(垂直、對角、隨機軌跡)以及性能優化建議。

一、核心邏輯:雙 Timer 往返移動

  • timer1:每 Tick 將 DesktopLocation.X += 1,向右移動
  • 到達右邊界(如 630)時,停用 timer1,啟用 timer2
  • timer2:每 Tick 將 DesktopLocation.X -= 1,向左移動
  • 到達左邊界(如 20)時,切回 timer1

二、完整可運行代碼

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 加平滑插值

四、性能與體驗優化

  1. 減少閃爍:this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
  2. 高 DPI 適配:使用 Screen.PrimaryScreen.WorkingArea 而非硬編碼邊界。
  3. CPU 佔用:Interval ≥ 10ms,Step ≤ 5px,避免佔用過高。
  4. 多顯示器:Screen.AllScreens 計算虛擬桌面邊界。
  5. 優雅退出:FormClosing 釋放 Timer、取消事件訂閱。

五、進階替代方案

  • WPF:DoubleAnimation + TranslateTransform,GPU 加速、聲明式、更流暢。
  • WinForms + AnimateWindow API:user32.dll AnimateWindow 系統級動畫,無需 Timer。
  • 屏保模式:命令列參數 /s /p /c 切換全屏/預覽/設置。

六、總結

雙 Timer + DesktopLocation 是 WinForms 實現窗體自動飄動最簡單、最直觀的方案。理解邊界檢測與狀態切換邏輯後,靈活組合即可創造各種趣味動畫。記住優化 DPI、多螢幕、CPU 佔用,才能從「能跑」進化為「好用」。

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