系统托盘的实现:
控件:NotifyIcon
// 点击最小化按钮则隐藏窗体,显示托盘图标
private void Form1_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized) //最小化
{
notifyIcon1.Visible = true; //托盘可见
this.Visible = false; //窗体不可见
}
else
{
notifyIcon1.Visible = false;
this.Visible = true;
}
}
// 左键双击托盘图标,显示窗体
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) //判断双击的是左键
{
this.Visible = true; //显示窗体
this.WindowState = FormWindowState.Normal;
this.Activate(); //获取焦点,将一个窗体显示在最前面
notifyIcon1.Visible = false; //托盘图标不可见
}
}
右键点击托盘图标,出现右键菜单项("显示","退出")
控件:ContextMenuStrip (上下文菜单)
在控件上添加“显示”、“退出”项;
将此上下文菜单关联到托盘控件上;(NotifyIcon控件的ContextMenuStrip属性设置为上下文菜单的对象)
单击这两菜单项的事件:
private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.Activate();
notifyIcon1.Visible = false;
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}