STEP1、添加托盘图标控件NotifyIcon(直接从工具箱中拖动添加即可)
STEP2、添加(重写)窗口尺寸变动函数Form1_Resize
private void Form1_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized) //最小化到系统托盘
{
NotifyIcon1.Visible = true; //显示托盘图标
this.Hide(); //隐藏窗口
}
}
STEP3、添加(重写)关闭窗口事件
private void Form1_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、添加托盘图标的右键菜单
(具体代码略)
"退出"菜单:Application.Exit();
"显示窗口"菜单:参考STEP4
PS: 解决了设置“关闭时隐藏到系统托盘”时,点击“退出”菜单也无法退出的问题。——无论是用this.Close();还是Application.Exit();都无法退出!——解决办法是,在关闭窗口事件中判断关闭原因/来源(e.CloseReason),若为CloseReason.UserClosing则为点击了窗口右上角的关闭按钮,否则可能是点击了"退出"菜单,则不执行隐藏到托盘的程序。(详见STEP3的if判断)
转载请注明出处hi.baidu.com/公子迅,谢谢大家的支持 ^_^
文章来自:
http://hi.baidu.com/%B9%AB%D7%D3%D1%B8/blog/item/485c090d2b4931d43bc76392.html
关键词:C#; WinForm; 系统托盘; 最小化; 关闭窗口; 无法退出