[英]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. 我们有一个位于后台的应用程序,利用
FileSystemWatcher
监视新文件的文件夹,当出现新文件时,它会产生一个窗口。
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? 所有关于如何实现系统托盘图标的搜索结果都指向如何将其添加到WPF窗口而不是应用程序本身的示例,因为我的应用程序没有主窗口并在事件发生时生成窗口我该如何才能实现这个?
Set the application ShutdownMode
to OnExplicitShutdown
and display the tray icon from the Application.OnStartup
. 将应用程序
ShutdownMode
设置为OnExplicitShutdown
并显示Application.OnStartup
的托盘图标。 This example uses the NotifyIcon
from WinForms
, so add a reference to System.Windows.Forms.dll
and System.Drawing.dll
. 此示例使用
WinForms
的NotifyIcon
,因此添加对System.Windows.Forms.dll
和System.Drawing.dll
的引用。 Also, add an embedded resource for the Tray Icon. 另外,为托盘图标添加嵌入式资源。
App.xaml 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 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");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.