C#关闭时最小化到系统托盘

Rak*_*esh 14 c# system-tray

嗨在我的c#应用程序中,当表单关闭时,我正在尝试最小化应用程序到系统托盘.这是我试过的代码.

   public void MinimizeToTray()
    {
        try
        {
            notifyIcon1.BalloonTipTitle = "Sample text";
            notifyIcon1.BalloonTipText = "Form is minimized";

            if (FormWindowState.Minimized == this.WindowState)
            {
                notifyIcon1.Visible = true;
                notifyIcon1.ShowBalloonTip(500);
                this.Hide();
            }
            else if (FormWindowState.Normal == this.WindowState)
            {
                notifyIcon1.Visible = false;
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }
Run Code Online (Sandbox Code Playgroud)

我正在调用形成结束事件的方法.但问题是它不能最小化托盘.它只是关闭表格.

小智 34

e.Cancel = true; 代码将始终取消该事件,即使您关闭计算机,但这里有一个代码可以帮助您:

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (e.CloseReason == CloseReason.UserClosing)
     {
          myNotifyIcon.Visible = true;
          this.Hide();
          e.Cancel = true;
     }
 }
Run Code Online (Sandbox Code Playgroud)

它将允许以programmaticaly方式关闭表单.


aru*_*cii 15

在Form Closing事件中写一个事件.

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
        e.Cancel = true;                         
        Hide();
 }
Run Code Online (Sandbox Code Playgroud)

并使用自定义菜单条写入要显示的通知图标.

  • 需要在构造函数中添加行:this.FormClosing + = this.Form1_FormClosing; (5认同)