STEP1、添加托盘图标控件NotifyIcon(直接从工具箱中拖动添加即可)
STEP2、添加(重写)窗口尺寸变动函数Form1_Resize
private void Main_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
notifyIcon1.Visible = true;
this.Hide();
}
}
STEP3、添加(重写)关闭窗口事件
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
//注意判断关闭事件Reason来源于窗体按钮,否则用菜单退出时无法退出!
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true; //取消"关闭窗口"事件
this.WindowState = FormWindowState.Minimized; //使关闭时窗口向右下角缩小的效果
notifyIcon1.Visible = true;
this.Hide();
return;
}
}
STEP4、添加双击托盘图标事件(双击显示窗口)
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
notifyIcon1.Visible = false;
this.Show();
WindowState = FormWindowState.Normal;
this.Focus();
}
STEP5、添加托盘图标的右键菜单
可以为notifyIcon1加一个ContextMenuStrip右键菜单
"退出"菜单:Application.Exit();