1、界面上拖拽添加NotifyIcon控件 notifyIcon1
2、为此控件设置图标
3、添加主界面最小化事件
private bool notifyiconHasInitialzed=false;//此变量用于控制避免重复执行后面的初始化函数
private void MF_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized) //判断是否最小化
{
notifyIcon1.Visible = true;
this.Hide();
this.ShowInTaskbar = false;
if (!notifyiconHasInitialzed)
Initializenotifyicon();
}
}
private void Initializenotifyicon()
{
//定义一个MenuItem数组,并把此数组同时赋值给ContextMenu对象
MenuItem[] mnuItms = new MenuItem[3];
mnuItms[0] = new MenuItem();
mnuItms[0].Text = "显示窗口";
mnuItms[0].Click += new System.EventHandler(this.notifyIcon1_showfrom);
mnuItms[1] = new MenuItem("-"); //在两个菜单项间显示横线
mnuItms[2] = new MenuItem();
mnuItms[2].Text = "退出系统";
mnuItms[2].Click += new System.EventHandler(this.ExitSelect);
mnuItms[2].DefaultItem = true;
//为托盘程序加入设定好的ContextMenu对象
ContextMenu notifyiconMnu = new ContextMenu(mnuItms);
notifyIcon1.ContextMenu = notifyiconMnu;
//添加图标单击事件
//关键要点:一定要避嫌此初始化函数在每次Mizmied事件时都重复执行,原因是如果下面Click委托事件被重复执行几次,每次点击时就会Click事件就会触发几次。这是+=事件的规律。
notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click);
notifyiconHasInitialzed = true;
}
//图标单击事件,后面的else if是为了实现能在显示和隐藏状态中直接切换,不用必须点击最小化按钮
private void notifyIcon1_Click(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized || !this.Visible)
{
this.Show();
this.ShowInTaskbar = true;
this.WindowState = FormWindowState.Normal;
//notifyIcon1.Visible = false;
}
else if (this.WindowState==FormWindowState.Normal || this.Visible)
this.Hide();
}
//下两个事件是右键菜单中对应的事件
public void notifyIcon1_showfrom(object sender, System.EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Show();
this.ShowInTaskbar = true;
this.WindowState = FormWindowState.Normal;
notifyIcon1.Visible = false;
}
}
public void ExitSelect(object sender, System.EventArgs e)
{
//隐藏托盘程序中的图标
notifyIcon1.Visible = false;
//关闭系统
this.Close();
this.Dispose(true);
}