在開發 Windows 桌面應用程式時,常見的需求是讓使用者點擊最小化按鈕時,視窗不會出現在工作列,而是縮小到系統托盤(通知區域)背景執行。這樣既不佔用工作列空間,又能讓程式持續運行。本文將詳細介紹如何在 C# WinForms 中實現這一功能,包含完整的程式碼範例與關鍵步驟解析。
實現最小化到托盤主要涉及兩個核心事件處理:
FormWindowState.Minimized 時,隱藏表單並顯示托盤圖示。你需要在表單上拖放一個 NotifyIcon 元件(位於工具箱的「Common Controls」分類),並設定其 Icon 屬性指定顯示在托盤的圖示。
private void Form1_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Visible = false; // 隱藏表單
this.notifyIcon1.Visible = true; // 顯示托盤圖示
}
}
private void notifyIcon1_Click(object sender, EventArgs e)
{
this.Visible = true; // 顯示表單
this.WindowState = FormWindowState.Normal; // 恢復正常大小
this.notifyIcon1.Visible = false; // 隱藏托盤圖示
}
為了提升使用者體驗,建議為 NotifyIcon 加上 ContextMenuStrip,提供「開啟」、「退出」等選項。同時,處理 MouseDoubleClick 事件可讓使用者雙擊圖示快速恢復視窗:
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.notifyIcon1.Visible = false;
}
}
FormClosing 事件中直接呼叫 Application.Exit(),程式會完全結束。若想讓「關閉按鈕」也最小化到托盤,需在 FormClosing 中取消關閉並執行隱藏邏輯:e.Cancel = true; this.Visible = false; notifyIcon1.Visible = true;NotifyIcon.Icon 使用 .ico 格式檔案,且已加入專案資源或輸出目錄。Invoke 避免跨執行緒例外。透過 Form.Resize 與 NotifyIcon 事件的簡單配合,即可輕鬆實現 WinForms 程式最小化至系統托盤。搭配右鍵選單與雙擊恢復,能打造出更專業、符合使用者習慣的桌面應用體驗。