[WinForm]最小化到系統托盤,右鍵退出
阿新 • • 發佈:2018-12-31
1.拉出一個notifyIcon1到使用者介面,也可以NEW一個
2.拉出一個ContextMenuStrip控制元件,命名為mymenu,集合中增加退出
3.notifyIcon1的屬性ContextMenuStrip 增加 myMenu;或者this.notifyIcon1.ContextMenuStrip = myMenu;
private void FrmMain_Load(object sender, EventArgs e) { //最小化到托盤 // this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components); // notifyIcon1.Icon = new Icon("2221.ico");//指定一個圖示 notifyIcon1.Visible = false; notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick); this.SizeChanged += new System.EventHandler(this.FrmMain_SizeChanged); }
/// <summary> /// 窗體大小改變事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FrmMain_SizeChanged(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized)//最小化 { this.ShowInTaskbar = false; this.notifyIcon1.Visible = true; } } /// <summary> /// 關閉窗體事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { DialogResult result = MessageBox.Show("是否退出?選否,最小化到托盤", "操作提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) { this.Dispose(); Application.Exit(); } else { e.Cancel = true; this.WindowState = FormWindowState.Minimized; this.Visible = false; this.notifyIcon1.Visible = true; } } /// <summary> /// 最小化圖示滑鼠事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { myMenu.Show(); } } /// <summary> /// 退出事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) { this.Dispose(); Application.Exit(); }
效果