自从.Net出现一个NotifyIcon控件,写系统托盘程序可以说是易如反掌。
本文不包含任何关于NotifyIcon的使用方法,只是谈一下几个开发系统托盘程序的相关问题。
1.如何防止程序多次运行?
[STAThread]
static void Main()
{
Process [] pss = System.Diagnostics.Process.GetProcesses();
for(int i=0;i<pss.Length;i++)
{
Process ps = pss[i];
if(ps.ProcessName == "MyNotifyApplication")
{
if(ps.Id != Process.GetCurrentProcess().Id)
{
return;
}
}
}
Application.Run(new Form1());
}
2.如何在最小化程序时隐藏窗体?
this.Resize += new System.EventHandler(this.Form1_Resize);
private void Form1_Resize(object sender, System.EventArgs e)
{
if(this.WindowState == FormWindowState.Minimized)
{
this.Hide();
}
}
3.如何在点击关闭按钮时隐藏窗体?
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if(!ClosedByPeople && !ClosedBySystem)
{
this.Hide();
e.Cancel = true;
}
}
4.如何确实要关闭程序?
private void menuExit_Click(object sender, System.EventArgs e)
{
ClosedByPeople = true;
this.Close();
}
5.系统关机或重启时,如何关闭程序?
private const int WM_QUERYENDSESSION=0x0011;
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
protected override void WndProc(ref Message m)
{
if(m.Msg == WM_QUERYENDSESSION)
{
ClosedBySystem = true;
}
base.WndProc (ref m);
}
以上代码都比较简单,所以就不做解释了,有问题可以留言。