1.拖一個NotifyIcon,一個ContextMenuStrip控制元件到主窗體中
2、設定notifyIcon1,一個contextMenuStrip1(如下圖)
Icon為托盤圖示,Text托盤顯示文字,ContextMenuStrip右鍵選單(退出),設定退出單擊事件
3、新增主窗體關閉事件(FormClosing)
4、事件程式碼
private void MyService_FormClosing(object sender, FormClosingEventArgs e) { // 注意判斷關閉事件reason來源於窗體按鈕,否則用選單退出時無法退出! if (e.CloseReason == CloseReason.UserClosing) { //取消"關閉視窗"事件 e.Cancel = true; //使關閉時視窗向右下角縮小的效果 this.WindowState = FormWindowState.Minimized; this.notifyIcon1.Visible = true; this.Hide(); return; } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { if (this.Visible) { this.WindowState = FormWindowState.Minimized; this.notifyIcon1.Visible = true; this.Hide(); } else { this.Visible = true; this.WindowState = FormWindowState.Normal; this.Activate(); } } private void MenuItemTuichu_Click(object sender, EventArgs e) { this.notifyIcon1.Visible = false; this.Close(); this.Dispose(); System.Environment.Exit(0); }