C# Minimize to system tray on close

Rakesh picture Rakesh · Nov 29, 2012 · Viewed 32.2k times · Source

Hi In my c# application I am trying to minimize application to systems tray, when the form is closed. Here is the code I have tried.

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

    }

and I am calling the method to form closing event. But the problem is its not minimizing to tray. Its just closing the form.

Answer

Emre picture Emre · May 27, 2013

e.Cancel = true; code will be always cancelling the event even if you shut the computer down, but here is a code that helps you:

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

It will allow closing the form programmaticaly.