C# WinForm視窗最小化到系統托盤右擊托盤圖示彈出退出選單
1. 在Form上加notifyicon控制元件myIcon,為控制元件的屬性Icon新增一個icon圖示, Text為滑鼠在圖示上時顯示的名字。
2. 新增ContextMenuStrip控制元件myMenu,右鍵托盤圖示彈出選單,設定myIcon的ContextMenuStrip屬性為myMenu。在myMenu中新增item(退出)。
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)//當用戶點選窗體右上角X按鈕或(Alt + F4)時 發生
{
e.Cancel = true;
this.ShowInTaskbar = false;
// this.myIcon.Icon = this.Icon;
this.Hide();
}
}
private void myIcon_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
myMenu.Show();
}
if (e.Button == MouseButtons.Left)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
}
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}