1. 程式人生 > >C#WinForm 藏到系統托盤

C#WinForm 藏到系統托盤

1 新增Form1_Load事件-啟動不顯示圖示

        private void Form1_Load(object sender, EventArgs e)
        {
            notifyIcon1.Visible = true;    //顯示托盤圖示
            this.Hide();    //隱藏視窗
        }
2 新增NotifyIcon控制元件-直接拖拽

3 為右鍵選單ContextMenuStrip-顯示和退出

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            this.Show();
            WindowState = FormWindowState.Normal;
            this.Focus();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
4 關聯右鍵選單

5 NotifyIcon左鍵點選事件

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                notifyIcon1.Visible = false;
                this.Show();
                WindowState = FormWindowState.Normal;
                this.Focus();
            }
        }
6 窗體關閉和改變大小
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)    //最小化到系統托盤
            {
                notifyIcon1.Visible = true;    //顯示托盤圖示
                this.Hide();    //隱藏視窗
            }
        }

        //關閉事件-檢測關閉位置[窗體上,還是托盤圖示]
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //注意判斷關閉事件Reason來源於窗體按鈕,否則用選單退出時無法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;    //取消"關閉視窗"事件
                this.WindowState = FormWindowState.Minimized;    //使關閉時視窗向右下角縮小的效果
                notifyIcon1.Visible = true;
                this.Hide();
                return;
            }
        }
*在關閉視窗事件中判斷關閉原因/來源(e.CloseReason),若為CloseReason.UserClosing則為點選了視窗右上角的關閉按鈕,否則可能是點選了"退出"選單,則不執行隱藏到托盤的程式。