You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止Windows通知点击触发.NET控制台程序重复启动?

解决Toast通知点击后重复启动程序的问题

我开发了一个基于.NET 4.7.2的控制台应用,使用Microsoft.Toolkit.Uwp.Notifications库创建Toast通知。通知可正常显示,但点击时会再次启动该.exe程序,导致通知反复弹出形成循环。期望点击通知时仅将其关闭或移入通知中心,请问需对以下代码做哪些修改?

Notification Image

原代码:

using Microsoft.Toolkit.Uwp.Notifications;
using System;
using Windows.Foundation.Collections;
using Windows.UI.Xaml.Controls;

namespace ToastTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // The ToastContentBuilder simplifies creating the notification.
            // This works in .NET Framework just like it did in .NET 8.
            new ToastContentBuilder()
                .AddText("Success on .NET Framework!")
                .AddText("This notification was sent using the Windows Community Toolkit.")
                .Show(); // The .Show() method handles the complex registration for you.

            // Console.WriteLine("Toast notification sent from .NET Framework! Check the Action Center.");
            // Console.ReadKey();
        }
    }
}

解决方案

出现循环的核心原因是:默认点击Toast会启动关联的控制台程序,而程序启动后又会立刻弹出新通知,形成闭环。需要通过两个关键修改解决:

1. 设置Toast的激活类型为None

通过SetToastActivationType方法将激活类型指定为ToastActivationType.None,这样点击通知只会关闭它,不会触发程序启动。

2. 增加启动参数判断(额外保险)

点击Toast启动程序时,系统会传递特定参数,通过检查启动参数可识别该场景,直接退出程序,避免意外触发新通知。

修改后的代码:

using Microsoft.Toolkit.Uwp.Notifications;
using System;
using Windows.UI.Notifications;

namespace ToastTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // 识别点击Toast启动的场景,直接退出
            if (args != null && args.Length > 0)
            {
                return;
            }

            new ToastContentBuilder()
                .AddText("Success on .NET Framework!")
                .AddText("This notification was sent using the Windows Community Toolkit.")
                // 设置点击通知仅关闭,不启动应用
                .SetToastActivationType(ToastActivationType.None)
                .Show();
        }
    }
}

说明

  • ToastActivationType.None是最贴合需求的设置,完全避免点击通知触发程序启动;
  • 启动参数判断是冗余防护,防止因系统或库的特殊情况导致激活类型设置失效,彻底阻断循环可能。

内容的提问来源于stack exchange,提问作者Fuzhen Tee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 14:54:55