Minimizing/Closing Application to system tray using WPF

Fahad picture Fahad · Dec 3, 2014 · Viewed 13.7k times · Source

I want to add application in System Tray when user minimize or close the form. I have done it for the Minimize case. Can anyone tell me that how i can keep my app running and add it into System Tray when I close the form?

public MainWindow()
    {
        InitializeComponent();
        System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
        ni.Icon = new System.Drawing.Icon(Helper.GetImagePath("appIcon.ico"));
        ni.Visible = true;
        ni.DoubleClick +=
            delegate(object sender, EventArgs args)
            {
                this.Show();
                this.WindowState = System.Windows.WindowState.Normal;
            };
        SetTheme();
    }

    protected override void OnStateChanged(EventArgs e)
    {
        if (WindowState == System.Windows.WindowState.Minimized)
            this.Hide();
        base.OnStateChanged(e);
    }

Answer

TheMiddleMan picture TheMiddleMan · Jun 28, 2016

You can also override OnClosing to keep the app running and minimize it to the system tray when a user closes the application.

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    // Minimize to system tray when application is minimized.
    protected override void OnStateChanged(EventArgs e)
    {
        if (WindowState == WindowState.Minimized) this.Hide();

        base.OnStateChanged(e);
    }

    // Minimize to system tray when application is closed.
    protected override void OnClosing(CancelEventArgs e)
    {
        // setting cancel to true will cancel the close request
        // so the application is not closed
        e.Cancel = true;

        this.Hide();

        base.OnClosing(e);
    }
}