[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();
            }

转载于:https://www.cnblogs.com/dooroo/archive/2012/09/09/2677315.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值