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); }