需求:應用程式啟動時不顯示主視窗,僅在系統通知區(托盤)顯示圖示,雙擊圖示再顯示視窗。本文比較三種作法優缺點。
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(false); // 永遠不顯示
}
Application.Exit() 結束,無法正常切換顯示/隱藏。static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
NotifyIcon ni = new NotifyIcon();
ni.Icon = Properties.Resources.AppIcon;
ni.Text = "我的應用程式";
ni.Visible = true;
ni.DoubleClick += (s, e) => { /* 顯示設定視窗 */ };
Application.Run(); // 無表單也能跑訊息迴圈
}
private bool _firstLoad = true;
protected override void OnActivated(EventArgs e)
{
if (_firstLoad)
{
this.Visible = false; // 啟動時隱藏
this.ShowInTaskbar = false; // 不顯示在工作列
_firstLoad = false;
}
base.OnActivated(e);
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (this.Visible)
{
this.Hide();
this.ShowInTaskbar = false;
}
else
{
this.Show();
this.ShowInTaskbar = true;
this.WindowState = FormWindowState.Normal;
this.BringToFront();
}
}
方法三平衡了開發便利性與使用者體驗,為最通用方案。搭配 ContextMenuStrip 可提供右鍵選單功能。
相關技巧: 開機自動啟動、單一執行個體應用、托盤氣球提示。