1 private NotifyIcon notifyIcon = null; //这里在窗体上没有拖拽一个NotifyIcon控件,而是在这里定义了一个变量 2 public Form1() 3 { 4 InitializeComponent(); 5 InitialTray(); //调用初始化托盘显示函数 6 } 7 8 private void Form1_FormClosing(object sender, FormClosingEventArgs e) 9 { 10 e.Cancel = true; //通过这里可以看出,这里的关闭其实不是真正意义上的“关闭”,而是将窗体隐藏,实现一个“伪关闭” 11 this.Hide(); 12 } 13 14 private void InitialTray() 15 { 16 17 this.Hide(); //隐藏主窗体 18 notifyIcon = new NotifyIcon(); //实例化一个NotifyIcon对象 19 notifyIcon.BalloonTipText = "正在运行"; //托盘图标气泡显示的内容 20 notifyIcon.Text = "ASCII码加密与解密软件"; //托盘图标显示的内容 21 string str = System.Windows.Forms.Application.StartupPath; 22 string str1 = string.Format("{0}/33.ico",str ); 23 24 // notifyIcon.Icon = new System.Drawing.Icon("G:/Visual Studio 2005/图标文件/33.ico"); //注意:下面的路径可以是绝对路径、相对路径。但是需要注意的是:文件必须是一个.ico格式 25 notifyIcon.Icon = new System.Drawing.Icon(str1); 26 notifyIcon.Visible = true; //true表示在托盘区可见,false表示在托盘区不可见 27 notifyIcon.ShowBalloonTip(2000);//气泡显示的时间(单位是毫秒) 28 notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseClick); 29 // MenuItem help = new MenuItem("帮助");//帮助选项,这里只是“有名无实”在菜单上只是显示,单击没有效果,可以参照下面的“退出菜单”实现单击事件 30 MenuItem about = new MenuItem("关于"); //关于选项 31 MenuItem exit = new MenuItem("退出"); 32 exit.Click += new EventHandler(exit_Click); //退出菜单项 33 about.Click += new EventHandler(about_Click); 34 ////关联托盘控件 35 //注释的这一行与下一行的区别就是参数不同,setting这个参数是为了实现二级菜单 36 //MenuItem[] childen = new MenuItem[] { setting, help, about, exit }; 37 MenuItem[] childen = new MenuItem[] { about, exit }; 38 notifyIcon.ContextMenu = new ContextMenu(childen); 39 this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);//窗体关闭时触发 40 41 } 42 43 private void notifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e) 44 { 45 46 if (e.Button == MouseButtons.Left) //鼠标左键单击 47 { 48 //如果窗体是可见的,那么鼠标左击托盘区图标后,窗体为不可见 49 if (this.Visible == false) 50 { 51 this.Visible = true; 52 } 53 else 54 { 55 this.Visible = true; 56 this.Activate(); 57 } 58 } 59 } 60 61 62 private void exit_Click(object sender, EventArgs e) 63 { 64 //退出程序 65 System.Environment.Exit(0); 66 }
时间: 2024-11-16 13:22:33