如何在没有“主”宿主窗口的情况下创建WPF系统托盘图标

11

背景

我们有一个应用程序,它在后台运行并利用FileSystemWatcher监视文件夹中的新文件,当出现新文件时,它会生成一个窗口。

我需要做的是为这个应用程序创建一个系统托盘图标,以便我们可以添加简单的上下文菜单项(最重要的是能够关闭应用程序而不必进入任务管理器)。

问题

所有关于如何实现系统托盘图标的搜索结果都是针对如何将其添加到WPF窗口而不是应用程序本身的示例,因为我的应用程序没有主窗口,并且在事件发生时生成窗口,那么我该如何实现呢?


2
请检查这篇文章:https://dev59.com/Y3M_5IYBdhLWcg3wNwUv - Dennis Traub
可能是 WPF Application that only has a tray icon 的重复问题。 - svick
1个回答

12

将应用程序的ShutdownMode设置为OnExplicitShutdown,并在Application.OnStartup中显示托盘图标。此示例使用 WinForms中的NotifyIcon,因此请添加对System.Windows.Forms.dllSystem.Drawing.dll的引用。同时,还需要为托盘图标添加嵌入式资源。

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
如果图标是通过项目属性中的资源添加的,则存在这样一个小差异:icon.Icon = MyApp.Properties.Resources.TrayIcon; - retroj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接