[英]How to create WPF System Tray Icon when no “Main” host window exists
背景
我們有一個位於后台的應用程序,利用FileSystemWatcher
監視新文件的文件夾,當出現新文件時,它會產生一個窗口。
我需要做的是為這個應用程序創建一個系統托盤圖標,以便我們可以向它添加簡單的上下文菜單項(能夠關閉應用程序而不進入任務管理器是最大的一個)。
題
所有關於如何實現系統托盤圖標的搜索結果都指向如何將其添加到WPF窗口而不是應用程序本身的示例,因為我的應用程序沒有主窗口並在事件發生時生成窗口我該如何才能實現這個?
將應用程序ShutdownMode
設置為OnExplicitShutdown
並顯示Application.OnStartup
的托盤圖標。 此示例使用WinForms
的NotifyIcon
,因此添加對System.Windows.Forms.dll
和System.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");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.