本文實例講述了WinForm實現最小化到系統托盤方法。分享給大家供大家參考。具體分析如下:
有個叫NotifyIcon的控件
1、建個WinForm項目,其它操作略過。
2、拉個NotifyIcon控件,將屬性Visable設置成False,在Text屬性上隨便填些文件。
3、實現Form的SizeChanged事件,代碼如下:
if(this.WindowState == FormWindowState.Minimized) //判斷是否最小化{this.ShowInTaskbar = false; //不顯示在系統任務欄notifyIcon.Visible = true; //托盤圖標可見}
4、實現NotifyIcon控件的DoubleClick事件,代碼如下:
if(this.WindowState == FormWindowState.Minimized){this.ShowInTaskbar = true; //顯示在系統任務欄this.WindowState = FormWindowState.Normal; //還原窗體notifyIcon.Visible = false; //托盤圖標隱藏}
例題:
private ContextMenu notifyiconMnu;#region 最小化到任務欄/// <summary>/// 最小化到任務欄/// </summary>private void Initializenotifyicon(){ //定義一個MenuItem數組,并把此數組同時賦值給ContextMenu對象 MenuItem[] mnuItms = new MenuItem[3]; mnuItms[0] = new MenuItem(); mnuItms[0].Text = "顯示窗口"; mnuItms[0].Click += new System.EventHandler(this.notifyIcon1_showfrom); mnuItms[1] = new MenuItem("-"); mnuItms[2] = new MenuItem(); mnuItms[2].Text = "退出系統"; mnuItms[2].Click += new System.EventHandler(this.ExitSelect); mnuItms[2].DefaultItem = true; notifyiconMnu = new ContextMenu(mnuItms); notifyIcon1.ContextMenu = notifyiconMnu; //為托盤程序加入設定好的ContextMenu對象 }private void notifyIcon1_DoubleClick(object sender, EventArgs e){ if (this.WindowState == FormWindowState.Minimized) { this.Show(); this.ShowInTaskbar = true; this.WindowState = FormWindowState.Normal; notifyIcon1.Visible = false; }}public void notifyIcon1_showfrom(object sender, System.EventArgs e){ if (this.WindowState == FormWindowState.Minimized) { this.Show(); this.ShowInTaskbar = true; this.WindowState = FormWindowState.Normal; notifyIcon1.Visible = false; }}public void ExitSelect(object sender, System.EventArgs e){ //隱藏托盤程序中的圖標 notifyIcon1.Visible = false; //關閉系統 this.Close(); this.Dispose(true);}#endregionprivate void Form_main_SizeChanged(object sender, EventArgs e){ if (this.WindowState == FormWindowState.Minimized) //判斷是否最小化 { notifyIcon1.Visible = true; this.Hide(); this.ShowInTaskbar = false; Initializenotifyicon(); }}
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答