C#:程式視窗關閉後,退到托盤圖示
阿新 • • 發佈:2018-12-27
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace WindowsFormsApp21 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //重寫Closing(),關閉視窗時不退出程式,而是顯示在托盤圖示 //需要先在介面中新增一個 NotifyIcon控制元件,然後設定一個圖示 //有右鍵選單,則再新增一個ContextMenuStrip private void Form1_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; //不退出程式 this.WindowState = FormWindowState.Minimized; //最小化 this.ShowInTaskbar = false; //在工作列中不顯示窗體 this.notifyIcon1.Visible = true; //托盤圖示可見 } //托盤圖示,滑鼠左鍵顯示回來原窗體,右鍵顯示退出 private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (this.WindowState == FormWindowState.Minimized) { this.Show(); this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; } } else { this.contextMenuStrip1.Show(Cursor.Position); } } //退出選單 private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem.Text.Equals("退出")) { this.Dispose(); this.Close(); } } } }