C# 最小化到系统托盘

来源:互联网 发布:gta5优化最好的盗版 编辑:程序博客网 时间:2024/05/22 06:36

      程序点击关闭后,弹出一个对话框,选择退出,最小化,或者取消.然后系统托盘双击,可以打开最小化的程序,右键有菜单,菜单里有个"选项",可以设置每次点击关闭按钮时是否弹出这个对话框。

      1.新建NotifyIconTest解决方案,在Form窗体框中添加NotifyIcon控件,命名为nIcon,在其属性Icon添加一个icon图标;然后添加一个ContextMenuStrip控件,命名为TuoPanContextMenuStrip,在里面添加两个ToolScripMenuItem,分别命名为MenuItemOpen,MenuItemClose。

      2.将nIcon的属性ContextMenuStrip设置成TuoPanContextMenuStrip。

      3.添加NotifyIcon控件的MouseDoubleClick事件;添加MenuItemOpen子菜单的Click事件和MenuItemClose子菜单的Click事件;添加Form窗体的SizeChanged事件。

     4.运行,测试,成功。

     源代码:

        /// <summary>
        /// 窗体大小改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmTP_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.Forms.FormWindowState.Minimized)
            {
                this.QPan_MiniMizedToTuoPan();
            }
        }
        //最小化托盘
        private void QPan_MiniMizedToTuoPan()
        {
            this.Hide();
            //window任务栏中是否显示窗体
            this.ShowInTaskbar = false;
            this.nIcon.Visible = true;

        }
        /// <summary>
        /// 双击托盘图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void nIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.QPan_OpenFromTuoPan();
        }
        //从托盘返回,函数
        private void QPan_OpenFromTuoPan()
        {
              this.Visible = true;
              this.Show();
              this.ShowInTaskbar = true;
              this.WindowState = System.Windows.Forms.FormWindowState.Normal;
              this.nIcon.Visible = true;
        }
        /// <summary>
        /// 打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemOpen_Click(object sender, EventArgs e)
        {
            this.QPan_OpenFromTuoPan();
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

效果如下:

点击最小化到托盘,双击图标恢复,右击图标显示菜单打开和关闭,点击关闭退出,点击打开,恢复。

原创粉丝点击