與C++相比c#提供的NotifyIcon控件實現托盤圖標容易了許多。
托盤程序的制作:
1.拖拽NotifyIcon控件到窗體上,並設置NotifyIcon的Icon(很重要!否則運行後看不到效果)
2.控制窗體最小化到托盤。
點擊(此處)折疊或打開
private void MinToIcon()
{
this.Hide();
this.ShowInTaskbar = false;
this.notifyIconCtrl.Visible = true;
}
private void ShowDlg()
{
this.Show();
this.ShowInTaskbar = true;
this.notifyIconCtrl.Visible = false;
}
3.創建菜單項:"顯示主窗體","退出" ,將菜單掛到NotifyIcon上。
點擊(此處)折疊或打開
private MenuItem showDlgMenu = new MenuItem("顯示窗體");
private MenuItem exitMenu = new MenuItem("退出");
this.showDlgMenu.Click += new EventHandler(showDlgMenu_Click);
this.exitMenu.Click += new EventHandler(exitMenu_Click);
this.notifyIconCtrl.ContextMenu = new System.Windows.Forms.ContextMenu();
this.notifyIconCtrl.ContextMenu.MenuItems.Add(this.showDlgMenu);
this.notifyIconCtrl.ContextMenu.MenuItems.Add(this.exitMenu);
private void btnMinToIcon_Click(object sender, EventArgs e)
{
MinToIcon();
}
void showDlgMenu_Click(object sender, EventArgs e)
{
ShowDlg();
}
void exitMenu_Click(object sender, EventArgs e)
{
this.Dispose(true);
Application.ExitThread();
}