1. 在Form上加notifyicon控件myIcon,为控件的属性Icon添加一个icon图标, Text为鼠标在图标上时显示的名字。
2. 添加ContextMenuStrip控件myMenu,右键托盘图标弹出菜单,设置myIcon的ContextMenuStrip属性为myMenu。在myMenu中添加item(退出)。
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();
}
}
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;
this.ShowInTaskbar = true;
}
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}