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?
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");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With