单击 toast 通知时防止再次打开应用程序

Prevent opening the app again when clicking on toast notification

我使用 Microsoft.Toolkit.Uwp.Notifications.ToastContentBuilder 在 WinForms 中为我的用户显示消息,它工作正常,但有时如果用户单击 toast,显示 toast 的程序会再次启动, 此外,如果应用已关闭,它会通过单击 toast 再次启动。

我希望 Toast 只发送一条消息,点击它什么也不做。任何帮助将不胜感激。

这是我的代码

new ToastContentBuilder()
   .AddText("testing")
   .AddText("testing").SetToastDuration(ToastDuration.Long).Show();

对于UWP应用程序,你需要后台激活,但是对于WinForms应用程序,如documentations中所述,你需要处理前台激活并且不显示任何UI,关闭应用

For desktop applications, background activations are handled the same as foreground activations (your OnActivated event handler will be triggered). You can choose to not show any UI and close your app after handling activation.

因此,为了防止在应用程序关闭时点击吐司时出现显示,请按照以下步骤操作:

  1. main 中调用 ToastNotificationManagerCompat.WasCurrentProcessToastActivated() 检查此实例是否为 toast-activated 实例(应用程序不是 运行 并且刚刚打开并激活以处理通知操作)然后不显示任何 window,否则显示主要 window.

  2. 同时处理 ToastNotificationManagerCompat.OnActivated 事件并检查它是否是一个 toast-activated 实例,然后什么都不做并退出应用程序。

示例 - 单击 toast 通知时停止再次打开应用程序

在下面的 .NET 6 示例中,我展示了一些消息框来帮助您区分应用程序是 toast-activated 还是 运行 实例。

using Microsoft.Toolkit.Uwp.Notifications;
using Windows.Foundation.Collections;
internal static class Program
{
    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        //Handle when activated by click on notification
        ToastNotificationManagerCompat.OnActivated += toastArgs =>
        {
            //Get the activation args, if you need those.
            ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
            //Get user input if there's any and if you need those.
            ValueSet userInput = toastArgs.UserInput;
            //if the app instance just started after clicking on a notification 
            if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated())
            {
                MessageBox.Show("App was not running, " +
                    "but started and activated by click on a notification.");
                Application.Exit();
            }
            else
            {
                MessageBox.Show("App was running, " +
                    "and activated by click on a notification.");
            }
        };
        if (ToastNotificationManagerCompat.WasCurrentProcessToastActivated())
        {
            //Do not show any window
            Application.Run();
        }
        else
        {
            //Show the main form
            Application.Run(new Form1());
        }
    }
}

了解更多: