Add a notification icon to your WPF program






I needed to create a WPF program that will run at certain intervals and, when running, always will do it in the background. Not that difficult. But I also wanted it to be accessible through a notification icon down in the right corner on the Windows screen. A little more work, but not that bad.

The result can be seen in these two pictures showing an active…

Notification icon when active

… and an in-active notification icon:

Notification icon






Below you’ll see the complete code. But before you can you it you’ll have to change a few things:

  • Add reference to System.Drawing and System.Windows.Forms
  • Add an icon to your project and set Build action to Resource in the icon’s Preferences
  • In the code snippet below, replace [program assembly name] with your program’s assembly name…
  • …and change to the correct icon file name on the same line of code.

And here is the code for the window.

public partial class MainWindow : Window
{
  System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
  public MainWindow()
  {
    InitializeComponent();

    // Initiate the notification icon
    Stream iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/[program assembly name];component/myicon.ico")).Stream;
    ni.Icon = new System.Drawing.Icon(iconStream);
    ni.Visible = true;  

    // When user double click the notification icon the program will open up
    ni.DoubleClick += delegate(object sender, EventArgs args) {
      this.Show();
      this.WindowState = WindowState.Normal;
    };

    this.Hide(); // The default start-up behaviour is hidden
  }

  protected override void OnStateChanged(EventArgs e)
  {
    // When minimized we only want to show the notification icon
    if (WindowState == WindowState.Minimized)
    {
      this.Hide();
    }
    base.OnStateChanged(e);
  }

  private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  {
    // Remove icon from taskbar when window is closing
    ni.Visible = false;
  }
}

The default behaviour for the program is now to hide the window from the beginning. When user double-clicks the notification icon the window opens up and the task-bar icon becomes visible as well, as shown in this picture. Mission accomplished!

Taskbar icon