Windows App SDK 1.2:主窗口关闭时如何让应用持续运行并显示托盘图标?
在Windows App SDK 1.2中实现主窗口关闭后保持运行并显示托盘图标
Windows App SDK没有直接对应WPF ShutdownMode="OnExplicitShutdown"的属性,需通过以下步骤实现需求:
1. 拦截主窗口关闭事件,阻止应用退出
在主窗口的Closing事件中取消默认关闭行为,改为隐藏窗口:
private void MainWindow_Closing(object sender, WindowClosingEventArgs args) { // 取消窗口销毁逻辑 args.Cancel = true; // 隐藏主窗口而非关闭 this.Hide(); }
2. 添加系统托盘图标
方案一:兼容式托盘图标(带右键菜单,推荐)
通过引用System.Windows.Forms和System.Drawing NuGet包实现完整托盘功能:
private System.Windows.Forms.NotifyIcon _trayIcon; private void InitializeTrayIcon() { _trayIcon = new System.Windows.Forms.NotifyIcon(); // 设置托盘图标(替换为你的图标路径) _trayIcon.Icon = new System.Drawing.Icon("Assets/AppIcon.ico"); _trayIcon.Visible = true; // 创建右键菜单 var contextMenu = new System.Windows.Forms.ContextMenuStrip(); contextMenu.Items.Add("显示主窗口", null, (s, e) => this.Show()); contextMenu.Items.Add("退出应用", null, (s, e) => ExitApplication()); _trayIcon.ContextMenuStrip = contextMenu; // 双击托盘图标显示主窗口 _trayIcon.DoubleClick += (s, e) => this.Show(); } private void ExitApplication() { // 清理托盘资源 _trayIcon.Visible = false; _trayIcon.Dispose(); // 显式终止应用 Microsoft.UI.Xaml.Application.Current.Exit(); }
在主窗口Loaded事件中调用InitializeTrayIcon()完成初始化。
方案二:WinUI 3原生通知图标
适合仅需后台通知场景,如需右键菜单需额外处理:
using Microsoft.UI.Notifications; using Windows.UI.Notifications; private void InitializeNativeTrayNotification() { // 创建后台运行提示通知 var toastXml = ToastNotificationManagerCompat.GetTemplateContent(ToastTemplateType.ToastImageAndText01); var textNodes = toastXml.GetElementsByTagName("text"); textNodes[0].AppendChild(toastXml.CreateTextNode("应用正在后台运行")); var toast = new ToastNotification(toastXml); toast.Tag = "BackgroundRunningTag"; ToastNotificationManagerCompat.CreateToastNotifier().Show(toast); // 点击通知恢复主窗口 ToastNotificationManagerCompat.OnActivated += (args) => { this.Show(); }; }
3. 维持后台运行状态
只要应用的App实例未被销毁,且托盘图标保持活跃,应用就会持续运行。仅当用户触发“退出应用”操作时,才调用Application.Current.Exit()显式终止。
注意事项
- 确保图标文件嵌入应用资源或路径正确,避免运行时加载失败
- 使用
System.Windows.Forms.NotifyIcon时注意线程安全,WinUI 3 UI线程需与WinForms操作同步 - 打包应用时,需将图标资源包含在安装包内
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

