c# 窗体最小化到托盘

c# winform最小化到托盘,也就是最小化到右下角,其实很简单,winform中有专门的控件。

下面是完整的代码,没太多需要解释的。

先在winform中添加notifyIcon控件,然后激活相应事件,添加代码。因为屏蔽了关闭窗体事件,可以设定一个全局变量bool变量来分辨是哪里引起的close事件。

注意添加Form的SizeChanged事件和NotifyIcon控件的DoubleClick事件

  1.       //全家变量bool closeTag = true;
  2.         //最小化
  3.         private void form1_Resize(object sender, EventArgs e)
  4.          {
  5.             if (this.WindowState == FormWindowState.Minimized)
  6.              {
  7.                  NormalToMinimized();
  8.              }           
  9.          }
  10.         //close时最小化
  11.         private void form1_FormClosing(object sender, FormClosingEventArgs e)
  12.          {
  13.              e.Cancel = true;
  14.              NormalToMinimized();
  15.          }
  16.         //单击显示窗体
  17.         private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
  18.          {
  19.             if (e.Button == MouseButtons.Left)
  20.              {
  21.                 this.MinimizedToNormal();
  22.              }
  23.          }
  24.         private void MinimizedToNormal()
  25.          {
  26.            this.Visible = true;
  27.            this.WindowState = FormWindowState.Normal;
  28.             notifyIcon.Visible = false;
  29.          }
  30.         private void NormalToMinimized()
  31.          {
  32.             this.WindowState = FormWindowState.Minimized;
  33.             this.Visible = false;
  34.             this.notifyIcon.Visible = true;
  35.          }
  36.         private void frmMain_FormClosing(object sender, FormClosingEventHandler e)
  37.          {
  38.             if (closeTag)
  39.              {
  40.                  e.Cancel = true;
  41.                  NormalToMinimized();
  42.              }
  43.          }
  44. //托盘右键关闭事件
  45.         private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
  46.          {
  47.              closeTag = false;
  48.              Application.Exit();
  49.          }

posted on 2009-10-22 12:56  秋天  阅读(1078)  评论(0编辑  收藏  举报

导航