共用方式為


從 C++ UWP 應用程式傳送本機 app 通知

通知 app 是一項訊息,您可以在用戶目前不在您的 app 時建構並送達給他們。

通知的 app 螢幕快照

本快速入門會逐步引導您完成使用豐富內容和互動式動作來建立、傳遞及顯示 Windows 10 或 Windows 11 app 通知的步驟。 本快速入門指南使用本機通知,這是最簡單實作的通知類型。 所有類型的應用程式(WPF、UWP、WinForms、控制台)都可以傳送通知!

Note

“toast notification” 一詞正取代為 “app notification”。 這些詞彙都是指 Windows 的相同功能,但隨著時間推移,我們將逐步在文件中淘汰「toast 通知」的使用。

Important

如果您要撰寫非 UWP app的C++,請參閱 C++ WRL 檔。 如果您要撰寫 C# ,請參閱 app 檔。

步驟 1:安裝 NuGet 套件

您可以使用 Windows Community Toolkit (WCT) 的建立器語法 OR 搭配 XML 來建立 app 通知。 如果您偏好後者,請跳至步驟 2,並參閱不使用建立器語法程式碼範例。

在 Visual Studio 解決方案中,以滑鼠右鍵按下您的專案,按兩下 [ 管理 NuGet 套件... ],然後搜尋並安裝 Microsoft.Toolkit.Uwp.NotificationsNuGet 套件 7.0 版或更新版本。

我們的 Builder 語法 程式碼範例將會使用此套件。 此套件可讓您建立 app 通知而不使用 XML。

步驟 2:新增命名空間宣告

using namespace Microsoft::Toolkit::Uwp::Notifications;

步驟 3:傳送 app 通知

在 Windows 10 和 Windows 11 中,您的 app 通知內容是使用調適型語言來描述,可讓您在通知外觀上具有極大的彈性。 如需詳細資訊,請參閱 App 通知內容 檔。

我們將從簡單的文字型通知開始。 建構通知內容(使用 Notifications 連結庫),並顯示通知! 請注意,命名空間為 Microsoft.Toolkit.Uwp.Notifications

簡單文字通知

如果您未使用 WCT 通知連結庫產生器語法,您會改為建構 XML app 通知範本、使用文字和值填入它、建構通知,並加以顯示。

// Construct the content and show the toast!
(ref new ToastContentBuilder())
    ->AddArgument("action", "viewConversation")
    ->AddArgument("conversationId", 9813)
    ->AddText("Andrew sent you a picture")
    ->AddText("Check this out, The Enchantments in Washington!")
    ->Show();

步驟 4:處理啟用

當使用者按下您的通知(或具有前景啟用之通知上的按鈕),將會叫用您app.xaml.cppAppOnActivated

App.xaml.cpp

void App::OnActivated(IActivatedEventArgs^ e)
{
    // Handle notification activation
    if (e->Kind == ActivationKind::ToastNotification)
    {
        ToastNotificationActivatedEventArgs^ toastActivationArgs = (ToastNotificationActivatedEventArgs^)e;

        // Obtain the arguments from the notification
        ToastArguments^ args = ToastArguments::Parse(toastActivationArgs->Argument);

        // Obtain any user input (text boxes, menu selections) from the notification
        auto userInput = toastActivationArgs->UserInput;

        // TODO: Show the corresponding content
    }
}

Important

您必須初始化框架並啟動視窗,就像 OnLaunched 程式碼一樣。 即使使用者按下您的 app 通知,並且 已關閉並首次啟動,仍然不會呼叫 OnLaunched。 我們通常會建議將 OnLaunchedOnActivated 結合成您自己的 OnLaunchedOrActivated 方法,因為兩者都需要進行相同的初始化。

全面啟用

讓您的通知具有可執行動作的第一步驟是將一些啟動參數新增至您的通知,如此一來,當使用者點擊通知時,您的 app 就能知道要啟動什麼(在此案例中,我們包含了一些資訊,稍後告訴我們應該開啟交談,並知道要開啟哪個特定交談)。

// Construct the content and show the toast!
(ref new ToastContentBuilder())

    // Arguments returned when user taps body of notification
    ->AddArgument("action", "viewConversation")
    ->AddArgument("conversationId", 9813)

    ->AddText("Andrew sent you a picture")
    ->Show();

新增圖片

您可以將豐富的內容新增至通知。 我們將新增內嵌影像和個人資料影像(app 標誌覆蓋)。

Note

您可以使用圖片,來源包括 app 的套件、app 的本機儲存空間,或來自網路。 從「Fall Creators Update」開始,網頁圖片在一般連線下最多可以為 3 MB,而在計量付費連線下則限制為 1 MB。 在尚未執行 Fall Creators Update 的裝置上,Web 映射不得大於 200 KB。

Toast 具有圖片
// Construct the content and show the toast!
(ref new ToastContentBuilder())
    ...

    // Inline image
    ->AddInlineImage(ref new Uri("https://picsum.photos/360/202?image=883"))

    // Profile (app logo override) image
    ->AddAppLogoOverride(ref new Uri("ms-appdata:///local/Andrew.jpg"), ToastGenericAppLogoCrop::Circle)

    ->Show();

新增按鈕和輸入

您可以新增按鈕和輸入,讓您的通知成為互動式通知。 按鈕可以啟動您的前景app、通訊協定或背景任務。 我們將新增回復文本框、[讚] 按鈕,以及開啟影像的 [檢視] 按鈕。

包含輸入和按鈕的通知之toast螢幕快照
// Construct the content
(ref new ToastContentBuilder())
    ->AddArgument("conversationId", 9813)
    ...

    // Text box for replying
    ->AddInputTextBox("tbReply", "Type a response")

    // Buttons
    ->AddButton((ref new ToastButton())
        ->SetContent("Reply")
        ->AddArgument("action", "reply")
        ->SetBackgroundActivation())

    ->AddButton((ref new ToastButton())
        ->SetContent("Like")
        ->AddArgument("action", "like")
        ->SetBackgroundActivation())

    ->AddButton((ref new ToastButton())
        ->SetContent("View")
        ->AddArgument("action", "view"))

    ->Show();

前景按鈕的激活會以與主要通知本文相同的方式進行處理(將會呼叫您的 App.xaml.cpp OnActivated)。

處理背景啟用

當您在通知上 app 指定背景啟用時(或在通知內的按鈕上),將會執行背景工作,而不是啟用前景 app。

如需了解背景工作的詳細資訊,請參閱 運用背景工作來支援您的 app

如果您的目標是組建 14393 或更新版本,則可以使用進程內背景工作,這可大幅簡化工作。 請注意,進程內背景工作將無法在舊版 Windows 上執行。 我們將在此程式代碼範例中使用處理程序中的背景任務。

const string taskName = "ToastBackgroundTask";

// If background task is already registered, do nothing
if (BackgroundTaskRegistration.AllTasks.Any(i => i.Value.Name.Equals(taskName)))
    return;

// Otherwise request access
BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();

// Create the background task
BackgroundTaskBuilder builder = new BackgroundTaskBuilder()
{
    Name = taskName
};

// Assign the toast action trigger
builder.SetTrigger(new ToastNotificationActionTrigger());

// And register the task
BackgroundTaskRegistration registration = builder.Register();

然後在您的 App.xaml.cs中,覆寫 OnBackgroundActivated 方法。 然後,您可以擷取預先定義的參數和使用者輸入,這與前景啟用相似。

App.xaml.cs

protected override async void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
    var deferral = args.TaskInstance.GetDeferral();

    switch (args.TaskInstance.Task.Name)
    {
        case "ToastBackgroundTask":
            var details = args.TaskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
            if (details != null)
            {
                string arguments = details.Argument;
                var userInput = details.UserInput;

                // Perform tasks
            }
            break;
    }

    deferral.Complete();
}

設定到期時間

在 Windows 10 和 11 中,所有 app 通知都會在使用者關閉或忽略後進入控制中心,讓使用者可以在快顯消失後查看您的通知。

不過,如果通知中的訊息只與一段時間有關,您應該在通知上 app 設定到期時間,讓使用者看不到來自 的 app過時資訊。 例如,如果促銷只有效 12 小時,請將到期時間設定為 12 小時。 在下列程式代碼中,我們將到期時間設定為 2 天。

Note

本機 app 通知的預設和最長到期時間為3天。

// Create toast content and show the toast!
(ref new ToastContentBuilder())
    ->AddText("Expires in 2 days...")
    ->Show(toast =>
    {
        toast->ExpirationTime = DateTime::Now->AddDays(2);
    });

請為您的通知設定主鍵app

如果您想要以程式設計方式移除或取代您傳送的通知,您必須使用Tag屬性(以及選擇性的 Group 屬性)來提供通知的主鍵。 然後,您可以在未來使用此主鍵來移除或取代通知。

若要查看取代/移除已傳遞 app 通知的詳細資訊,請參閱 快速入門:在控制中心 (XAML) 中管理 toast 通知

標記與群組的結合共同構成一個複合主鍵。 Group 是較通用的標識符,您可以在其中指派 “wallPosts”、“messages”、“friendRequests” 等群組。然後 Tag 應該從群組內唯一識別通知本身。 藉由使用泛型群組,您就可以使用 RemoveGroup API 從該群組移除所有通知。

// Create toast content and show the toast!
(ref new ToastContentBuilder())
    ->AddText("New post on your wall!")
    ->Show(toast =>
    {
        toast.Tag = "18365";
        toast.Group = "wallPosts";
    });

清除您的通知

應用程式會負責移除和清除自己的通知。 啟動 app 後,我們不會自動清除您的通知。

只有在使用者明確按一下通知時,Windows 才會自動移除通知。

以下是傳訊 app 應該執行的範例...

  1. 使用者會收到關於交談中新訊息的多個 app 通知
  2. 用戶點選其中一個通知來開啟交談
  3. app啟動對話,然後會清除所有該對話的通知(透過使用 RemoveGroup 在app提供的該對話群組上)
  4. 使用者的動作中心現在會正確反映通知狀態,因為動作中心中沒有留下該會話的過時通知。

若要瞭解如何清除所有通知或移除特定通知,請參閱 快速入門:在控制中心 (XAML) 中管理 toast 通知

ToastNotificationManagerCompat::History->Clear();

Resources