【问题标题】:How to create WPF System Tray Icon when no "Main" host window exists不存在“主”主机窗口时如何创建 WPF 系统托盘图标
【发布时间】:2011-07-07 12:31:08
【问题描述】:

背景

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

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

问题

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

【问题讨论】:

标签: wpf system-tray


【解决方案1】:

将应用程序ShutdownMode 设置为OnExplicitShutdown 并显示Application.OnStartup 中的托盘图标。此示例使用来自WinFormsNotifyIcon,因此添加对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");
        }
    }
}

【讨论】:

  • 如果图标是通过项目属性中的资源添加的,有这个小区别:icon.Icon = MyApp.Properties.Resources.TrayIcon;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2018-03-07
相关资源
最近更新 更多