[转载]C#WinForm程序设计——系统托盘NotifyIcon控件

1.如何实现托盘功能:
在VS2005中直接添加notifyIcon控件,然后设置下icon属性,给其设置个图标即可,使用托盘功能.
但是托盘并不能实现我们要求的功能,具体的功能实现,需要我们手工添加代码实现.
2.如何最小化时自动到托盘

 1  private void Form1_SizeChanged(object sender, EventArgs e)
 2  {
 3       if (WindowState == FormWindowState.Minimized)
 4       {
 5           this.Hide();
 6           this.notifyIcon1.Visible = true;
 7           this.notifyIcon1.ShowBalloonTip(30, "注意", "大家好,这是一个事例", ToolTipIcon.Info);
 8       }
 9 
10  }
11  private void Form1_SizeChanged(object sender, System.EventArgs e) 
12  { 
13      if (this.WindowState == FormWindowState.Minimized) 
14      { 
15          this.Visible = false; 
16          this.notifyIcon1.Visible = true; 
17      } 
18 } 

3.如何双击托盘恢复原状

private void notifyIcon1_MouseDoubleClick(object sender, System.EventArgs e) 
{ 
   this.Visible = true; 
   this.WindowState = FormWindowState.Normal; 
   this.notifyIcon1.Visible = false; 
} 

 


4.实现托盘的闪烁功能(如QQ有消息时的闪烁)
  (1).首先我们在空白窗体中拖入一个NotifyIcon控件和定时控件

  private System.Windows.Forms.NotifyIcon notifyIcon1;
  private System.Windows.Forms.Timer timer1;

  (2).其次,我们准备两张ico图片,用来显示在任务栏,其中一张可用透明的ico图片,分别叫做1.ico和2.ico;并且建立两个icon对象分别用来存放两个ico图片;

  private Icon ico1 = new Icon("1.ico");
  private Icon ico2 = new Icon("2.ICO");//透明的图标

  (3).在Form_load中初始化notifyicon:

  private void Form1_Load(object sender, System.EventArgs e)
  {
      this.notifyIcon1.Icon=ico1;//设置程序刚运行时显示在任务栏的图标
      this.timer1.Enable = true;//将定时控件设为启用,默认为false;
  }

 


  (4).先设置一个全局变量 i ,用来控制图片索引,然后创建定时事件,双击定时控件就可以编辑

  int i=0;
  private void timer1_Tick(object sender, System.EventArgs e)
  {
      //如果i=0则让任务栏图标变为透明的图标并且退出
      if(i<1)
      {
          this.notifyIcon1.Icon=ico2;
          i++;
          return;
      }
      //如果i!=0,就让任务栏图标变为ico1,并将i置为0;
      else
      this.notifyIcon1.Icon=ico1;
      i=0;

(2)NotifyIcon控件的doubleclick事件及两个menuitem的click事件:

private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal; } private void toolStripMenuItem2_Click(object sender, EventArgs e) { this.Close(); } private void toolStripMenuItem1_Click(object sender, EventArgs e) { this.notifyIcon1.Visible = false; this.Show(); this.WindowState = FormWindowState.Normal; } private void Form1_FormClosing(object sender, FormClosingEventArgs e)//点关闭隐藏程序 { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true;
notifyIcon1.Visible
= true; this.WindowState = FormWindowState.Minimized; this.Visible = false; notifyIcon1.ShowBalloonTip(1, "提示", "程序依然在运行!", ToolTipIcon.Info); } }
posted @ 2012-09-14 23:46  Mr.Left  阅读(342)  评论(0编辑  收藏  举报