1、界面上拖拽添加NotifyIcon控件 notifyIcon1
2、為此控件設置圖標
3、添加主界面最小化事件
private bool notifyiconHasInitialzed=false;//此變量用於控制避免重復執行后面的初始化函數
private void MF_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized) //判斷是否最小化
{
notifyIcon1.Visible = true;
this.Hide();
this.ShowInTaskbar = false;
if (!notifyiconHasInitialzed)
Initializenotifyicon();
}
}
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;
//為托盤程序加入設定好的ContextMenu對象
ContextMenu notifyiconMnu = new ContextMenu(mnuItms);
notifyIcon1.ContextMenu = notifyiconMnu;
//添加圖標單擊事件
//關鍵要點:一定要避嫌此初始化函數在每次Mizmied事件時都重復執行,原因是如果下面Click委托事件被重復執行幾次,每次點擊時就會Click事件就會觸發幾次。這是+=事件的規律。
notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click);
notifyiconHasInitialzed = true;
}
//圖標單擊事件,后面的else if是為了實現能在顯示和隱藏狀態中直接切換,不用必須點擊最小化按鈕
private void notifyIcon1_Click(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized || !this.Visible)
{
this.Show();
this.ShowInTaskbar = true;
this.WindowState = FormWindowState.Normal;
//notifyIcon1.Visible = false;
}
else if (this.WindowState==FormWindowState.Normal || this.Visible)
this.Hide();
}
//下兩個事件是右鍵菜單中對應的事件
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);
}