C#做托盘程序

所谓托盘程序顾名思义就是象托起的盘子一样的程序。而所谓的托起的盘子就是程序运行中显示出的图标,而托起的位置就是视窗系统的的工具栏了。托盘程序具有直观、占用屏幕空间较小并且可以为它定义多个功能菜单,这就给操作者带来了方便,所以越来越多的程序设计者都把程序设计成托盘这种方式。我们已经看过了用其他语言设计托盘程序的例子,其中的大部分,整个设计过程还是相对烦琐的。而对于微软公司极力推荐的下一代程序开发语言--Visual C#来说,却可以十分方便设计出一个托盘程序。本文就是介绍Visual C#设计托盘程序的具体过程。

  首先来介绍一下本文中设计托盘程序所需要的环境:

  (1).微软公司视窗2000服务器版

  (2)..Net FrameWork SDK Beta 2

  一. 托盘程序的主要步骤及解决方法:

  为什么说用Visual C#可以十分方便的做一个托盘程序,主要的原因是在.Net框架的软件开发包( .Net FrameWork SDK )中的WinForm组件中定义了一个专门用来开发托盘程序的组件--NotifyIcon组件。下面就来介绍一下这个组件的具体用法和程序设计中的主要的技巧。

  (1).如何在程序运行后隐藏窗体:

  我们知道托盘程序运行后是无法看见主窗体的,他只会显示在工具栏上。在用Visual C#设计此类程序的时候,可以用二种方法使得程序运行后不显示主窗体。其中一种方法是重载主窗体中的OnActivated( )事件,OnActivated( )事件是在窗体激活的时候才触发的。通过重载此事件可以达到隐藏主窗体的目的。具体程序代码如下:

protected override void OnActivated ( EventArgs e )
{
this.Hide ( ) ;
}

  另外一种方法是在初始化主窗体的时候完成的,通过设定主窗体的属性来达到不显示的目的。具体的程序代码如下:

this.MaximizeBox = false ;
this.MinimizeBox = false ;
this.WindowState = System.Windows.Forms.FormWindowState.Minimized ;

  在本文介绍的程序中,使用了第二种方法。
(2).如何为托盘程序设定显示图标:

  在NotifyIcon组件中有一个属性icon就是来设定托盘图标的,由于Visual C#是一个完全的OOP (面向对象)语言,在Visual C#中任何东西都可以作为对象来处理。当然对应一个icon来说,也可以用对象的方法来处理他。我们通过下列语句来得到一个icon对象:

private Icon mNetTrayIcon = new Icon ( "Tray.ico" ) ;

  请注意:在编译好的程序中,必须要在同一个目录中有一个Tray.ico图标文件,否则程序运行时候会出错的。

  通过下列语句把此icon对象付给NotifyIcon组件中的icon属性,此时如果程序正确编译,则此icon就会显示在工具栏中了。

TrayIcon.Icon = mNetTrayIcon ;

  (3).设定当鼠标停留在托盘程序上显示的文本内容:

  NotifyIcon组件中有一个属性Text。设定这个属性的内容,就是鼠标停留在托盘图标上显示的内容了。具体语句如下:

TrayIcon.Text = "用Visual C#做托盘程序" + "\n" + "作者:****2010.03.08" ;

  (4).如何在托盘程序加入菜单:

  在NotifyIcon组件中有一个对象叫ContextMenu,在托盘程序中显示出的菜单就是通过设定此对象来实现的。以下的程序代码是为托盘程序加入菜单项:

notifyiconMnu = new ContextMenu ( mnuItms ) ;
TrayIcon.ContextMenu = notifyiconMnu ;
//为托盘程序设定菜单

  (5).如何设定ContextMenu对象的内容:

  ContextMenu对象是托盘程序的菜单的结构,所以如何设定此对象,在本程序中是比较关键的。在程序中,是通过定义一个菜单项数组,并对这个数组设定不同的值(这当中包括菜单的一些属性和事件),然后把这个数组同时赋值给ContextMenu对象,来实现对ContextMenu对象的设置过程的。以下是程序中具体代码:

//定义一个MenuItem数组,并把此数组同时赋值给ContextMenu对象
MenuItem [ ] mnuItms = new MenuItem [ 3 ] ;
mnuItms [ 0 ] = new MenuItem ( ) ;
mnuItms [ 0 ] .Text = "用Visual C#做托盘程序!" ;
mnuItms [ 0 ] .Click += new System.EventHandler ( this.showmessage ) ;

mnuItms [ 1 ] = new MenuItem ( "-" ) ; 
mnuItms [ 2 ] = new MenuItem ( ) ;
mnuItms [ 2 ] .Text = "退出系统" ;
mnuItms [ 2 ] .Click += new System.EventHandler ( this.ExitSelect ) ;
mnuItms [ 2 ] .DefaultItem = true ;

notifyiconMnu = new ContextMenu ( mnuItms ) ;
TrayIcon.ContextMenu = notifyiconMnu ;
//为托盘程序加入设定好的ContextMenu对象

  当成功加入了ContextMenu对象后,在程序编译完成运行时,当鼠标右键点击托盘图标,程序会自动弹出ContextMenu对象封装好的菜单。

  二. 本文介绍的程序源代码( Tray.cs ):
Tray.cs源程序代码:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
namespace WindowsFormsAppTry
{
    public class Tray:Form
    {
        private System.ComponentModel.Container components = null;
        private Icon mNetTrayIcon = new Icon("C:\\Documents and Settings\\Administrator\\桌面\\桌面\\vs2010 Code\\WindowsFormsAppTry\\WindowsFormsAppTry\\drugstore.ico");
        private NotifyIcon TrayIcon;
        private ContextMenu notifyiconMnu;
        public Tray()
        {
            //初始化窗体中使用到的组件
            InitializeComponent();
            //初始化托盘程序的各个要素
            Initializenotifyicon();
        }
        private void Initializenotifyicon()
        {
            //设定托盘程序的各个属性
            TrayIcon = new NotifyIcon();
            TrayIcon.Icon = mNetTrayIcon;
            TrayIcon.Text = "用Visual C#做托盘程序" + "\n" + "作者:Hyey.Leo_wl于2010.03.08";
            TrayIcon.Visible = true;
            TrayIcon.Click += new System.EventHandler(this.click);

            //定义一个MenuItem数组,并把此数组同时赋值给ContextMenu对象
            MenuItem[] mnuItms = new MenuItem[3];
            mnuItms[0] = new MenuItem();
            mnuItms[0].Text = "用Visual C#做托盘程序!";
            mnuItms[0].Click += new System.EventHandler(this.showmessage);

            mnuItms[1] = new MenuItem("-");

            mnuItms[2] = new MenuItem();
            mnuItms[2].Text = "退出系统";
            mnuItms[2].Click += new System.EventHandler(this.ExitSelect);
            mnuItms[2].DefaultItem = true;

            notifyiconMnu = new ContextMenu(mnuItms);
            TrayIcon.ContextMenu = notifyiconMnu;
            //为托盘程序加入设定好的ContextMenu对象
        }
        public void click(object sender, System.EventArgs e)
        {
            MessageBox.Show("Visual C#编写托盘程序中的事件响应");
        }

        public void showmessage(object sender, System.EventArgs e)
        {
            MessageBox.Show("你点击了菜单的第一个选项");
        }

        public void ExitSelect(object sender, System.EventArgs e)
        {
            //隐藏托盘程序中的图标
            TrayIcon.Visible = false;
            //关闭系统
            this.Close();
        }
        //清除程序中使用过的资源
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(320, 56);
            this.ControlBox = false;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.WindowState = System.Windows.Forms.FormWindowState.Minimized;

            this.Name = "tray";
            this.ShowInTaskbar = false;
            this.Text = "用Visual C#做托盘程序!";
            this.ResumeLayout(false);

        }

        static void Main()
        {
            Application.Run(new Tray());
        }
    }
}

//----------------------------------------------------------------

using System;
using System.Drawing;using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace Notify{
 /// <summary> /// Form1 的摘要说明。
 /// </summary> 
public class Form1 : 
System.Windows.Forms.Form { 
 private System.Windows.Forms.MainMenu mainMenu1;
  private System.Windows.Forms.MenuItem menuItem1;
  private System.Windows.Forms.MenuItem menuItem4; 
 private System.Windows.Forms.MenuItem menuItem2; 
 private System.Windows.Forms.NotifyIcon notifyIcon1;  
private System.Windows.Forms.MenuItem menuItem3; 
 private System.Windows.Forms.ContextMenu contextMenu1;  
private System.Windows.Forms.PictureBox pictureBox1; 
 private System.Windows.Forms.MenuItem menuItem5;  
private System.Windows.Forms.MenuItem menuItem6;  
private System.Windows.Forms.MenuItem menuItem7; 
 private System.Windows.Forms.MenuItem menuItem8; 
 private System.ComponentModel.IContainer components;  public Form1()  
{   //   // Windows 窗体设计器支持所必需的   //   InitializeComponent();   //   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码   //  } 
 /// <summary>  /// 清理所有正在使用的资源。  /// </summary> 
 protected override void Dispose( bool disposing )  {   if( disposing )  
 {    if (components != null)     {     components.Dispose();    }   }   base.Dispose( disposing );  } 
 #region Windows 窗体设计器生成的代码  /// <summary>  /// 设计器支持所需的方法 - 不要使用代码编辑器修改  /// 此方法的内容。  /// </summary> 
 private void InitializeComponent()  {           
 this.components = new System.ComponentModel.Container();           
 System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));           
 this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);            

this.menuItem1 = new System.Windows.Forms.MenuItem();            
this.menuItem2 = new System.Windows.Forms.MenuItem();            
this.menuItem5 = new System.Windows.Forms.MenuItem();           
 this.menuItem3 = new System.Windows.Forms.MenuItem();            
this.menuItem6 = new System.Windows.Forms.MenuItem();            
this.menuItem7 = new System.Windows.Forms.MenuItem();          
  this.menuItem8 = new System.Windows.Forms.MenuItem();         
   this.menuItem4 = new System.Windows.Forms.MenuItem();           
 this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);           
 this.contextMenu1 = new System.Windows.Forms.ContextMenu();           
 this.pictureBox1 = new System.Windows.Forms.PictureBox();          
  ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();        
    this.SuspendLayout();          
  //             // mainMenu1            //             
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {            
this.menuItem1});            //             // menuItem1            //             this.menuItem1.Index = 0;          
  this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {           
 this.menuItem2,        
    this.menuItem5,       
     this.menuItem3,          
  this.menuItem6,         
   this.menuItem7,         
  this.menuItem8,         
   this.menuItem4});            this.menuItem1.Text = "视图(&V)";            
//             // menuItem2            //          
  this.menuItem2.Index = 0;           
 this.menuItem2.Text = "放置到系统托盘(&N)";        
    this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);          
  //             // menuItem5            //          
   this.menuItem5.Index = 1;     
       this.menuItem5.Text = "-";          
  //             // menuItem3            //             this.menuItem3.Index = 2;         
   this.menuItem3.Text = "恢复正常显示(&R)";           
 this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click);        
    //             // menuItem6            //          
   this.menuItem6.Index = 3;            this.menuItem6.Text = "-";         
   //             // menuItem7            //            
 this.menuItem7.Index = 4;            this.menuItem7.Text = "托盘和窗体同时显示(&T)";         
   this.menuItem7.Click += new System.EventHandler(this.menuItem7_Click);        
    //             // menuItem8            //          
   this.menuItem8.Index = 5;            this.menuItem8.Text = "-";          
  //             // menuItem4            //         
    this.menuItem4.Index = 6;            this.menuItem4.Text = "关闭(&C)";          
  this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click);           
 //             // notifyIcon1            //           
  this.notifyIcon1.ContextMenu = this.contextMenu1;           
 this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));        
    this.notifyIcon1.Text = "这是一个演示托盘的实例程序";       
     //             // pictureBox1            //          
   this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;       
     this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));   
         this.pictureBox1.Location = new System.Drawing.Point(0, 0);     
       this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(411, 286);       
     this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;       
     this.pictureBox1.TabIndex = 0;      
      this.pictureBox1.TabStop = false;         
   //             // Form1            //           
  this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);          
  this.ClientSize = new System.Drawing.Size(411, 286);       
     this.Controls.Add(this.pictureBox1);          
 this.Menu = this.mainMenu1;          
  this.Name = "Form1";        
    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;       
     this.Text = "演示如何使用托盘控件";       
     this.Load += new System.EventHandler(this.Form1_Load);     
       ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); 
           this.ResumeLayout(false);  }  #endregion
  /// <summary>  
/// 应用程序的主入口点。  
/// </summary> 
 [STAThread] 
 static void Main()   
{   Application.Run(new Form1());  }
    private void menuItem4_Click(object sender, System.EventArgs e) 
 {//关闭应用程序   this.notifyIcon1.Visible=false;   this.Close();   Application.Exit();  } 
 private void menuItem2_Click(object sender, System.EventArgs e) 
 {//显示托盘图标    this.Visible=false;    this.notifyIcon1.Visible=true;  }  
private void menuItem3_Click(object sender, System.EventArgs e)
  {//显示主窗体   this.Visible=true;   this.notifyIcon1.Visible=false;    } 
 private void Form1_Load(object sender, System.EventArgs e) 
 {//复制主菜单的菜单项到上下文菜单   //复制到“放置到系统托盘(N)”菜单项   this.contextMenu1.MenuItems.Add(this.menuItem2.CloneMenu());   
//复制分隔线菜单项   this.contextMenu1.MenuItems.Add(this.menuItem5.CloneMenu());  
  //复制到“恢复正常显示(R)”菜单项   this.contextMenu1.MenuItems.Add(this.menuItem3.CloneMenu()); 
  //复制分隔线菜单项   this.contextMenu1.MenuItems.Add(this.menuItem6.CloneMenu());  
 //复制到“关闭(C)”菜单项   this.contextMenu1.MenuItems.Add(this.menuItem4.CloneMenu());    
//复制分隔线菜单项   this.contextMenu1.MenuItems.Add(this.menuItem8.CloneMenu());    
//复制到“托盘和窗体同时显示(T)”菜单项   this.contextMenu1.MenuItems.Add(this.menuItem7.CloneMenu()); 
   //this.contextMenu1.MergeMenu(this.mainMenu1.);  }  private void menuItem7_Click(object sender, System.EventArgs e)  
{//托盘和窗体同时显示   this.Visible=true;   this.notifyIcon1.Visible=true;      } }} 

  三. 总结:

  通过以上介绍,可以看出用Visual C#做一个托盘程序并不是一件复杂的事情,而是一件比较轻松的事情。同样也可使我们明白,Visual C#虽然是一种功能强大的程序设计语言,但它只是一个打开.Net FrameWork SDK的钥匙,正是这个内容丰富的软件包,才使得各个.Net程序开发语言有了施展自身功能更广阔的舞台。

原文地址:https://www.cnblogs.com/Leo_wl/p/1687850.html