我使用 Microsoft.Toolkit.Uwp.Notifications.ToastContentBuilder 在 WinForms 中為我的用戶顯示訊息,它作業正常,但有時如果用戶單擊 toast,顯示 toast 的程式會再次啟動,如果應用程式是關閉它通過單擊吐司再次啟動。
我希望吐司只發送一條訊息,點擊它什么也不做。任何幫助將不勝感激。
這是我的代碼
new ToastContentBuilder()
.AddText("testing")
.AddText("testing").SetToastDuration(ToastDuration.Long).Show();
uj5u.com熱心網友回復:
對于 UWP 應用程式,您需要后臺激活,但對于 WinForms 應用程式,如檔案中所述,您需要處理前臺激活并且不顯示任何 UI,關閉應用程式。
對于桌面應用程式,后臺激活的處理方式與前臺激活相同(您的 OnActivated 事件處理程式將被觸發)。您可以選擇不顯示任何 UI 并在處理激活后關閉您的應用程式。
因此,為了防止在應用程式關閉時單擊 toast 時顯示顯示,請執行以下步驟:
在中
main,呼叫ToastNotificationManagerCompat.WasCurrentProcessToastActivated()來檢查這個實體是否是一個 toast 激活的實體(應用程式沒有運行并且剛剛打開并激活以處理通知操作)然后不顯示任何視窗,否則顯示主視窗.還要處理ToastNotificationManagerCompat.OnActivated事件并檢查它是否是 toast 激活的實體,然后什么也不做,只退出應用程式。
示例 - 單擊 toast 通知時停止再次打開應用程式
在下面的 .NET 6 示例中,我展示了一些訊息框來幫助您區分應用程式是 Toast 激活的還是正在運行的實體的情況。
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());
}
}
}
了解更多:
- 從 C# 應用程式發送本地 toast 通知
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431271.html
