zoukankan      html  css  js  c++  java
  • [C#]winform窗口托盘

    [C#]winform窗口托盘
        winform托盘的使用主要用到了两个控件notifyIcon和contextMenuStrip
        (一)notifyIcon的使用
        1)先在工具箱中拖到主窗体中,直接在属性icon中选择一个ICO图标作为托盘图标,并把主窗口的属性ShowInTaskbar是否出现在任务栏中设置为假
        2)添加以下事件和语句
            private void Form1_SizeChanged(object sender, EventArgs e)
            {//窗口尺寸改变事件:即点最小化时(最好窗口是固定大小)
                if (this.WindowState == FormWindowState.Minimized)
                {
                    this.Hide();//隐藏主窗口
                    this.notifyIcon1.Visible = true;//托盘为真
                }
            }
            //双击托盘,窗口恢复正常
            private void notifyIcon1_DoubleClick(object sender, EventArgs e)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
        3)这里涉及到如果窗口有关闭按钮(最好是自己做关闭按钮),把关闭按钮改为最小化
         protected override void WndProc(ref   Message m) 
     {//重装API中的关闭 
          const int WM_SYSCOMMAND = 0x0112; 
          const int SC_CLOSE = 0xF060; 
          if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE) 
           {//捕捉关闭窗体消息    
              this.WindowState = FormWindowState.Minimized; 
              return; 
           } 
          base.WndProc(ref   m); 
     }
        如果是自己做的关闭按钮,直接用第2)步的方法即可.

        (二)为了让托盘图标有右键菜单功能,需要添加contextMenuStrip
        1)从工具箱中拖contextMenuStrip控件到主窗体
        2)为contextMenuStrip设置菜单项
        3)为notifyIcon属性中关联contextMenuStrip
        4)假设双击托盘或托盘菜单中"显示主窗口":
            //双击托盘,窗口恢复正常
            private void notifyIcon1_DoubleClick(object sender, EventArgs e)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
            //菜单:显示主窗口
            private void 主窗口_Click(object sender, EventArgs e)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
            //菜单:退出功能
            private void 退出_Click(object sender, EventArgs e)
            {
                this.Close();
            }
    另:如果想加一个关闭窗口时提示:确定退出?"是"则退出,"否"则最小化,并提供一个checkbox记住以后都按相同的操作,还会有一点麻烦,下次再研究.

                if (MessageBox.Show("确定退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    Application.Exit();
                }

  • 相关阅读:
    express实现前后端通信上传图片,存储数据库(mysql)傻瓜教程(二)
    express实现前后端通信上传图片,存储数据库(mysql)傻瓜教程(一)
    [转载] 在阿里做了五年技术主管,我有话想说
    阿里云RDS MySql还原到本地Linux/Centos
    如何领域驱动设计?-实践感悟&总结分享
    jira + confluence 安装和破解
    RabbitMQ安装和配置
    [转]技术路线的选择重要但不具有决定性
    .Net core2.0日志组件Log4net、Nlog简单性能测试
    在微服务中使用领域事件
  • 原文地址:https://www.cnblogs.com/dooroo/p/2677315.html
Copyright © 2011-2022 走看看