C#托盘程序示例
先拖一个NotifyIcon控件,注意:notifyIcon1.Icon=new Icon("Zipped 4.ico")图标文件路径及名字,否则抛异常
代码
public MainForm()
{
InitializeComponent();
InitNotifyIcon();
}
private void InitNotifyIcon()
{
MenuItem[] mi=new MenuItem[3];
mi[0]=new MenuItem();
mi[0].Text="显示";
mi[0].Click+= new EventHandler(this.FormShow);
mi[1]=new MenuItem();
mi[1].Text="-";
mi[2]=new MenuItem();
mi[2].Text="退出";
mi[2].Click+=new EventHandler(this.FormClose);
ContextMenu cm=new ContextMenu(mi);
notifyIcon1.MouseDoubleClick+=new MouseEventHandler(notifyIcon1_MouseDoubleClick);
notifyIcon1.Icon=new Icon("Zipped 4.ico");
notifyIcon1.Text="已运行 - \\\\数据上报程序";
notifyIcon1.Visible=true;
notifyIcon1.ContextMenu=cm;
}
private void FormShow(object sender, EventArgs e)
{
this.Visible=true;
}
private void FormClose(object sender, EventArgs e)
{
this.Close();
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Visible=true;
}
const int WM_SYSCOMMAND = 0x112;
const int SC_CLOSE = 0xF060;
const int SC_MINIMIZE = 0xF020;
const int SC_MAXIMIZE = 0xF030;
protected override void WndProc(ref Message m)
{
if(m.Msg==WM_SYSCOMMAND)
{
if(m.WParam.ToInt32()==SC_CLOSE)
{
this.Visible=false;
return;
}
if(m.WParam.ToInt32()==SC_MINIMIZE)
{
this.Visible=false;
return;
}
}
base.WndProc(ref m);
}
{
InitializeComponent();
InitNotifyIcon();
}
private void InitNotifyIcon()
{
MenuItem[] mi=new MenuItem[3];
mi[0]=new MenuItem();
mi[0].Text="显示";
mi[0].Click+= new EventHandler(this.FormShow);
mi[1]=new MenuItem();
mi[1].Text="-";
mi[2]=new MenuItem();
mi[2].Text="退出";
mi[2].Click+=new EventHandler(this.FormClose);
ContextMenu cm=new ContextMenu(mi);
notifyIcon1.MouseDoubleClick+=new MouseEventHandler(notifyIcon1_MouseDoubleClick);
notifyIcon1.Icon=new Icon("Zipped 4.ico");
notifyIcon1.Text="已运行 - \\\\数据上报程序";
notifyIcon1.Visible=true;
notifyIcon1.ContextMenu=cm;
}
private void FormShow(object sender, EventArgs e)
{
this.Visible=true;
}
private void FormClose(object sender, EventArgs e)
{
this.Close();
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Visible=true;
}
const int WM_SYSCOMMAND = 0x112;
const int SC_CLOSE = 0xF060;
const int SC_MINIMIZE = 0xF020;
const int SC_MAXIMIZE = 0xF030;
protected override void WndProc(ref Message m)
{
if(m.Msg==WM_SYSCOMMAND)
{
if(m.WParam.ToInt32()==SC_CLOSE)
{
this.Visible=false;
return;
}
if(m.WParam.ToInt32()==SC_MINIMIZE)
{
this.Visible=false;
return;
}
}
base.WndProc(ref m);
}