Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Minimize to system tray on close

Tags:

c#

system-tray

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.

like image 712
Rakesh Avatar asked Nov 29 '12 11:11

Rakesh


2 Answers

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.

like image 126
Emre Avatar answered Oct 13 '22 01:10

Emre


Write a event in Form Closing event.

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
        e.Cancel = true;                         
        Hide();
 }

And write using Custom menu strip for notification icon for to show.

like image 43
Arunkumar Chandrasekaran Avatar answered Oct 12 '22 23:10

Arunkumar Chandrasekaran