C# WinForms 動態設定小圖示

在執行 WinForm 應用程式時在 WinForm 視窗的左上角和系統工具列上的小圖示是預設的 icon,可以改變嗎?

當然,而且非常簡單!只要先依照 C# WinForms 儲存圖片資源 這篇文章中的步驟將圖片儲存在資源中,然後將圖片轉換為 icon 並設定 form 的 icon 即可!
    

Bitmap bitmap = Resources.ruyut;
this.Icon = Icon.FromHandle(bitmap.GetHicon());
    

為了方便確認「動態變更」,我們動態增加一個 Button ,在 Button 的點擊事件中替換 icon
    

Bitmap bitmap = Resources.ruyut;

Button button = new()
{
    Location = new Point(50, 50),
    Size = new Size(100, 100),
    Text = "Set Icon",
};
this.Controls.Add(button);
button.Click += (sender, args) => { this.Icon = Icon.FromHandle(bitmap.GetHicon()); };
    

這樣在執行時就會看到原本左上角和系統工具列的 icon 都是預設,按下後就會自動變為自己設定的圖案了!

留言