C#实现系统托盘
1.设置窗体属性ShowInTaskbar=false
2.加notifyicon控件notifyicon1,为控件notifyicon1的属性icon添加一个icon图标。
3.添加触发事件
代码
//窗体最小化
private void FrmMain_SizeChanged(object sender, EventArgs e)
{
if(this.WindowState==FormWindowState.Minimized)
{
this.Visible = false;
this.WindowState = FormWindowState.Minimized;
this.notifyIcon1.Visible = true;
}
}
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
{
this.notifyIcon1.Visible = true;
}
else
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.notifyIcon1.Visible = false;
}
}
private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
{
this.notifyIcon1.Visible = false;
}
private void FrmMain_SizeChanged(object sender, EventArgs e)
{
if(this.WindowState==FormWindowState.Minimized)
{
this.Visible = false;
this.WindowState = FormWindowState.Minimized;
this.notifyIcon1.Visible = true;
}
}
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
{
this.notifyIcon1.Visible = true;
}
else
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
this.notifyIcon1.Visible = false;
}
}
private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
{
this.notifyIcon1.Visible = false;
}
4.可以给notifyicon添加右键菜单:
主窗体中拖入一个contextmenu控件contextmenu1,点中控件,在上下文菜单中添加菜单,notifyicon1的contextmenu行为中选中contextmenu1作为上下文菜单。