C# 托盘程序编写
我使用的环境:Visual Studio 2005 Professoinal Edition 
注意:Windows窗体生成器生成的代码中不能加注释,即使加了注释也会被自动去掉! 
使用NotifyIcon控件,该控件的作用是程序运行时在Windows任务栏右侧的通知区域中(任务栏)显示图标。 使用contextMenuStrip控件,该控件可以关联到其它控件,作用是当右击关联的控件时显示菜单。 在NotifyIcon1的属性列表中的contextMenuStrip的下拉列表中选择你刚才创建的contextMenuStrip1菜单。你的托盘程序就拥有一个菜单了。 接下来的与通常图形界面程序的编写相同,首先在[设计]窗口中设计你的界面,然后双击做好的菜单或按钮进入代码窗口写对应的代码。 接下来是一些托盘程序所应具有的一些特别功能的代码 
为托盘程序设置双击托盘图标显示/隐藏窗口
首先是在Windows 窗体设计器生成的代码中为托盘图标增加双击事件,具体做法是在具有托盘图标的Form的designer.cs中找到notifyIcon的部分,加入语句
 this.notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
this.notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
其作用是重载notifyIcon1的双击事件,为其添加方法notifyIcon1_DoubleClick(注意,这里的notifyIcon1和notifyIcon1_DoubleClick可以由你自己设定,可能与这里不同)。
接着我们来实现notifyIcon1_DoubleClick方法,在Form的Class中写方法:
 private void notifyIcon1_DoubleClick(object sender, EventArgs e)
private void notifyIcon1_DoubleClick(object sender, EventArgs e) 2
 {
{ 3
 this.Show();
this.Show(); 4
 if (this.WindowState == FormWindowState.Minimized)
if (this.WindowState == FormWindowState.Minimized) 5
 this.WindowState = FormWindowState.Normal;
this.WindowState = FormWindowState.Normal; 6
 else if (this.WindowState == FormWindowState.Normal)
else if (this.WindowState == FormWindowState.Normal) 7
 this.WindowState = FormWindowState.Minimized;
this.WindowState = FormWindowState.Minimized; 8
 this.Activate(); //激活窗体并为其赋予焦点
this.Activate(); //激活窗体并为其赋予焦点 9
 }
} 10

最小化时隐藏窗体(隐藏任务栏上的项目)
首先同样是修改窗体设计器自动生成的代码,在Form1(假设,可能不同)中增加语句
然后实现Form1_Resize方法:
 private void Form1_Resize(object sender, System.EventArgs e)
private void Form1_Resize(object sender, System.EventArgs e) 2
 {
{ 3
 if (this.WindowState == FormWindowState.Minimized)
if (this.WindowState == FormWindowState.Minimized) 4
 {
{ 5
 this.Hide();
this.Hide(); 6
 }
} 7
 }
}
将关闭按钮重载为最小化
 protected override void OnFormClosing(FormClosingEventArgs e)
protected override void OnFormClosing(FormClosingEventArgs e) 2
 {
{ 3
 if (!CloseTag)
if (!CloseTag) 4
 {
{ 5
 this.WindowState = FormWindowState.Minimized;
this.WindowState = FormWindowState.Minimized; 6
 e.Cancel = true;
e.Cancel = true; 7
 }
} 8
 else
else 9
 e.Cancel = false;
e.Cancel = false; 10
 base.OnFormClosing(e);
base.OnFormClosing(e); 11
 }
} 12

这里需要说明的是,我的Form1有一个Bool型私有变量CloseTag,另外我的程序有一个关闭按钮,该按钮才是真正的关闭程序。我的做法是当使用我的关闭按钮时将CloseTag设为True,否则CloseTag为false。这样就做到了完整的关闭重载。
 
                     
                    
                 
                    
                 



 
                
            
        