1. 在Form上加notifyicon控件myIcon,为控件的属性Icon添加一个icon图标, Text为鼠标在图标上时显示的tip。
2. 在Form1_FormClosing中设置Form的ShowInTaskbar属性
3. 在myIcon_MouseClick事件中设置Form的ShowInTaskbar和WindowState属性
4. 添加ContextMenuStrip控件myMenu,右键托盘图标弹出菜单,设置myIcon的ContextMenuStrip属性为myMenu。在myMenu中添加item(退出)。
5. myIcon在MouseClick事件中,判断右键点击 并弹出ContextMenuStrip。
代码:
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;
}
}
private void toolMenuCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}