1. 程式人生 > >WinForm中實現最小化到系統托盤

WinForm中實現最小化到系統托盤

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

        #endregion
private void Form_main_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized) //判斷是否最小化
            {
                notifyIcon1.Visible = true;
                this.Hide();
                this.ShowInTaskbar = false;

                Initializenotifyicon();
            }
        }