首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# WinForm 實現窗體背景圖片定時輪播:Timer 控件配合 ImageList 切換圖片

     編輯:程式設計綜合問答
完整代碼
public partial class MainForm : Form {
    private int imgIndex = 0;

    public MainForm() {
        InitializeComponent();
        // 1. 準備 ImageList
        imageList1.Images.Add(Image.FromFile("bg1.jpg"));
        imageList1.Images.Add(Image.FromFile("bg2.jpg"));
        imageList1.Images.Add(Image.FromFile("bg3.jpg"));
        imageList1.Images.Add(Image.FromFile("bg4.jpg"));

        // 2. 設置 Timer
        timer1.Interval = 5000; // 5 秒
        timer1.Enabled = true;
        timer1.Tick += Timer1_Tick;

        // 3. 初始背景
        this.BackgroundImage = imageList1.Images[0];
    }

    private void Timer1_Tick(object sender, EventArgs e) {
        imgIndex = (imgIndex + 1) % imageList1.Images.Count;
        this.BackgroundImage = imageList1.Images[imgIndex];
    }
}

關鍵點

  • ImageList 統一管理圖片資源,避免重複載入。
  • Timer 觸發 Tick 事件在 UI 線程安全更新 BackgroundImage。
  • 取模運算 % 實現循環輪播。

進階優化

  • 使用 BackgroundImageLayout = ImageLayout.Stretch 自適應窗體大小。
  • 圖片資源嵌入為嵌入資源,避免部署路徑問題。
  • 淡入淡出效果可用雙 PictureBox 疊加 + Opacity 動畫實現。

總結

幾行代碼即可實現專業級背景輪播,核心在於 ImageList 資源管理與 Timer 定時觸發。

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