Minimize an Application to the System Tray


To be able to use the System Tray in Visual Studio, drag and drop the NotifyIcon control. The important properties to set are Text and Icon. The Icon is displayed in the tray, and the contents of the Text property will be displayed in a Tooltip when the user hovers the mouse over the icon in the tray. Because we want to display the NotifyIcon only when the user minimizes the main window, the Visible property should be set to False, and set to True programmatically when the form is minimized.

    //this field holds the window state (minimized, maximized or normal)
    //before minimizing. it will be used when displaying the form again
    private FormWindowState currentState;

    private void mainFrom_Load(object sender, EventArgs e)
    {
        //initialize the field to the current window state
        currentState = this.WindowState;
    }

    private void mainFrom_Resize(object sender, EventArgs e)
    {
        if (this.WindowState == FormWindowState.Minimized)
        {                
            this.Visible = false;
            notifyIcon1.Visible = true;  //display tray icon
        }
        else
        {
            //if the form is not being minimized, save its state
            currentState = this.WindowState;
        }
    }

    private void sysTrayIcon_Click(object sender, EventArgs e)
    {
        this.Visible = true;
        notifyIcon1.Visible = false;

        //set to state before minizing
        this.WindowState = currentState;            
    }