C#实现托盘应用程序

下面是我根据网络上的应用程序改编的一个简单的托盘程序的DEMO,实现了一般托盘程序的基本功能

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication4
{
    public partial class Form1 : Form
    {

        private Icon mNetIcon = new Icon("appMain.ico");

        private NotifyIcon TrayIcon;

        private ContextMenu notifyiconMnu;


        public Form1()
        {
            InitializeComponent();
            Initializenotifyicon();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.WindowState = System.Windows.Forms.FormWindowState.Minimized;


        }

        private void Initializenotifyicon()
        {
            //设定托盘程序的各个属性
            TrayIcon = new NotifyIcon();
            TrayIcon.Icon = mNetIcon;
            TrayIcon.Text = "用Visual C#做托盘程序";
            TrayIcon.Visible = true;
            TrayIcon.Click += new System.EventHandler(this.click);

            ////定义一个MenuItem数组,并把此数组同时赋值给ContextMenu对象
            MenuItem[] mnuItms = new MenuItem[1];
            mnuItms[0] = new MenuItem();
            mnuItms[0].Text = "退出系统";
            mnuItms[0].Click += new System.EventHandler(this.showmessage);

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

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            TrayIcon.Visible = false;
        }
        public void click(object sender, System.EventArgs e)
        {
            MessageBox.Show("Visual C#编写托盘程序中的事件响应");
        }

        public void showmessage(object sender, System.EventArgs e)
        {
            MessageBox.Show("你选择了退出系统!");
            this.Close();
        }

    }
}

posted on 2010-03-29 18:09  一路前行  阅读(878)  评论(0编辑  收藏  举报