How to create WPF System Tray Icon when no "Main" host window exists
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 implemen开发者_JS百科t 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");
}
}
}
精彩评论