百度空间 | 百度首页 
               
 
查看文章
 
C# 托盘程序编写的总结
2008-08-04 13:59

我的一点小小经验,总结在这里,备忘。

我使用的环境:Visual Studio 2005 Professoinal Edition

注意:Windows窗体生成器生成的代码中不能加注释,即使加了注释也会被自动去掉!

  1. 使用NotifyIcon控件,该控件的作用是程序运行时在Windows任务栏右侧的通知区域中(任务栏)显示图标。
  2. 使用contextMenuStrip控件,该控件可以关联到其它控件,作用是当右击关联的控件时显示菜单。
  3. 在NotifyIcon1的属性列表中的contextMenuStrip的下拉列表中选择你刚才创建的contextMenuStrip1菜单。你的托盘程序就拥有一个菜单了。
  4. 接下来的与通常图形界面程序的编写相同,首先在[设计]窗口中设计你的界面,然后双击做好的菜单或按钮进入代码窗口写对应的代码。

接下来是一些托盘程序所应具有的一些特别功能的代码

  1. 为托盘程序设置双击托盘图标显示/隐藏窗口
    首先是在Windows 窗体设计器生成的代码中为托盘图标增加双击事件,具体做法是在具有托盘图标的Form的designer.cs中找到notifyIcon的部分,加入语句

    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)

{

    this.Show();

    if (this.WindowState == FormWindowState.Minimized)

    this.WindowState = FormWindowState.Normal;

    else if (this.WindowState == FormWindowState.Normal)

    this.WindowState = FormWindowState.Minimized;

    this.Activate(); //激活窗体并为其赋予焦点

}

  1. 最小化时隐藏窗体(隐藏任务栏上的项目)
    首先同样是修改窗体设计器自动生成的代码,在Form1(假设,可能不同)中增加语句

    this.Resize += new System.EventHandler(this.Form1_Resize);

    然后实现Form1_Resize方法:

private void Form1_Resize(object sender, System.EventArgs e)

{

    if (this.WindowState == FormWindowState.Minimized)

     {

    this.Hide();

     }

}

  1. 将关闭按钮重载为最小化

protected override void OnFormClosing(FormClosingEventArgs e)

{

    if (!CloseTag)

{

    this.WindowState = FormWindowState.Minimized;

     e.Cancel = true;

     }

    else

     e.Cancel = false;

    base.OnFormClosing(e);

}

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


类别:.net 开发 | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu