需要在form窗体中引入NotifyIcon组件,取名为myIcon
private ContextMenu notifyIconContextMenu;
private MenuItem menuItemExit;
private void Form1_Load(object sender, EventArgs e){
this.ShowInTaskbar = false;
this.myIcon.Icon = this.Icon;
this.Hide();
notifyIconContextMenu = new ContextMenu();
menuItemExit = new MenuItem("关闭程序");
menuItemExit.Click += MenuItemExit_Click;
notifyIconContextMenu.MenuItems.Add(menuItemExit);
myIcon.ContextMenu = notifyIconContextMenu;
}
private void MenuItemExit_Click(object sender, EventArgs e)
{
Application.Exit(); // 关闭应用程序
}
private void myIcon_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
//myMenu.Show();
}
if (e.Button == MouseButtons.Left)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)//当用户点击窗体右上角X按钮或(Alt + F4)时 发生
{
e.Cancel = true;
this.ShowInTaskbar = false;
this.myIcon.Icon = this.Icon;
this.Hide();
}
}