首页 > Windows开发 > 详细

winform最小化到托盘,托盘右击菜单显示

时间:2016-11-24 08:29:43      阅读:313      评论:0      收藏:0      [点我收藏+]

添加notifyIcon控件,并添加Icon,否则托盘没有图标(托盘右键菜单也可直接在属性里添加);

主要的代码:

public partial class Form1 : Form
    {
        #region
        //创建NotifyIcon对象 
        NotifyIcon notifyicon = new NotifyIcon();
        //创建托盘图标对象 
        Icon ico = new Icon("u9.ico");
        //创建托盘菜单对象 
        ContextMenu notifyContextMenu = new ContextMenu();
        #endregion
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //设置鼠标放在托盘图标上面的文字 
            this.notifyIcon1.Text = "码农网测试";
        }

        /// <summary>
        /// 最小化到托盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮 
            if (WindowState == FormWindowState.Minimized)
            {
                //托盘显示图标等于托盘图标对象 
                //注意notifyIcon1是控件的名字而不是对象的名字 
                notifyIcon1.Icon = ico;
                //隐藏任务栏区图标 
                this.ShowInTaskbar = false;
                //图标显示在托盘区 
                notifyicon.Visible = true;
            }
        }


        /// <summary>
        /// 托盘单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            { 
                case System.Windows.Forms.MouseButtons.Left:    //左击
                    //判断是否已经最小化于托盘 
                    if (WindowState == FormWindowState.Minimized)
                    {
                        //还原窗体显示 
                        WindowState = FormWindowState.Normal;
                        //激活窗体并给予它焦点 
                        this.Activate();
                        //任务栏区显示图标 
                        this.ShowInTaskbar = true;
                        //托盘区图标隐藏 
                        notifyicon.Visible = false;
                    }
                    break;
                case System.Windows.Forms.MouseButtons.Right:
                    //MessageBox.Show("右键");
                    break;
            }
        }
    }

 

winform最小化到托盘,托盘右击菜单显示

原文:http://www.cnblogs.com/testsec/p/6095874.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!