11

Background

We have an application that sits in the background and utilizes FileSystemWatcher to monitor a folder for new files, when a new file appears it spawns a window.

What I need to do is create a system tray icon for this application so that we can add simple context menu items to it (being able to close the app without going into task manager is the biggest one).

Question

All of the search results for how to implement a system tray icon point to examples of how to add it to a WPF window not the application itself, since my app doesn't have a main window and spawns windows when an event occurs how can I implement this?

2

1 Answer 1

12

Set the application ShutdownMode to OnExplicitShutdown and display the tray icon from the Application.OnStartup. This example uses the NotifyIcon from WinForms, so add a reference to System.Windows.Forms.dll and System.Drawing.dll. Also, add an embedded resource for the Tray Icon.

App.xaml

<Application x:Class="WpfTrayIcon.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             ShutdownMode="OnExplicitShutdown"
             >
    <Application.Resources>

    </Application.Resources>
</Application>

App.xaml.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Windows;

using NotifyIcon = System.Windows.Forms.NotifyIcon;

namespace WpfTrayIcon
{
    public partial class App : Application
    {
        public static NotifyIcon icon;

        protected override void OnStartup(StartupEventArgs e)
        {
            App.icon = new NotifyIcon();
            icon.Click += new EventHandler(icon_Click);
            icon.Icon = new System.Drawing.Icon(typeof(App), "TrayIcon.ico");
            icon.Visible = true;

            base.OnStartup(e);
        }

        private void icon_Click(Object sender, EventArgs e)
        {
            MessageBox.Show("Thanks for clicking me");
        }
    }
}
1
  • 1
    If the icon is added via Resources in project properties, there is this small difference: icon.Icon = MyApp.Properties.Resources.TrayIcon;
    – retroj
    Mar 30, 2017 at 1:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.