如果您正在開發一個非 C# 或 C++ 的未封裝 app,則本主題對您有用。
也就是說,如果您未開發已封裝app的專案(請參閱為封裝的 WinUI 3 桌面app建立新專案),而且您並未開發使用外部位置封裝的套件app(請參閱使用外部位置封裝來授與套件身分識別),而您的 app 不是 C# 或C++。
未使用您的 app 時,app 可以建構並傳遞通知 app 給使用者。 本快速入門會逐步引導您完成建立、傳遞及顯示 Windows app 通知的步驟。 本快速入門指南使用本機通知,這是最簡單實作的通知類型。
Note
“toast notification” 一詞正取代為 “app notification”。 這些詞彙都是指 Windows 的相同功能,但隨著時間推移,我們將逐步在文件中淘汰「toast 通知」的使用。
步驟 1:在註冊表中註冊您的app
您首先需要在登錄中註冊您app的資訊,包括識別您app的唯一AUMID、app的顯示名稱、圖示和COM啟動器的GUID。
<registryKey keyName="HKEY_LOCAL_MACHINE\Software\Classes\AppUserModelId\<YOUR_AUMID>">
<registryValue
name="DisplayName"
value="My App"
valueType="REG_EXPAND_SZ" />
<registryValue
name="IconUri"
value="C:\icon.png"
valueType="REG_EXPAND_SZ" />
<registryValue
name="IconBackgroundColor"
value="AARRGGBB"
valueType="REG_SZ" />
<registryValue
name="CustomActivator"
value="{YOUR COM ACTIVATOR GUID HERE}"
valueType="REG_SZ" />
</registryKey>
步驟 2:設定 COM 啟動器
即使當您的 app 未執行時,也可以隨時點擊通知。 因此,通知啟用是透過 COM 啟動器來處理。 COM 類別必須實作 INotificationActivationCallback 介面。 COM 類別的 GUID 必須符合您在註冊表 CustomActivator 值中指定的 GUID。
struct callback : winrt::implements<callback, INotificationActivationCallback>
{
HRESULT __stdcall Activate(
LPCWSTR app,
LPCWSTR args,
[[maybe_unused]] NOTIFICATION_USER_INPUT_DATA const* data,
[[maybe_unused]] ULONG count) noexcept final
{
try
{
std::wcout << this_app_name << L" has been called back from a notification." << std::endl;
std::wcout << L"Value of the 'app' parameter is '" << app << L"'." << std::endl;
std::wcout << L"Value of the 'args' parameter is '" << args << L"'." << std::endl;
return S_OK;
}
catch (...)
{
return winrt::to_hresult();
}
}
};
步驟 3:傳送 app 通知
在 Windows 10 中,您的 app 通知內容會使用調適型語言來描述,讓您在通知的外觀上具有極大的彈性。 如需詳細資訊, App 請參閱通知內容 檔。
我們將從簡單的文字型通知開始。 建構通知內容(使用 Notifications 連結庫),並顯示通知!
Important
傳送通知時,您必須使用先前的 AUMID,如此一來,通知就會從 您的 app出現。
// Construct the toast template
XmlDocument doc;
doc.LoadXml(L"<toast>\
<visual>\
<binding template=\"ToastGeneric\">\
<text></text>\
<text></text>\
</binding>\
</visual>\
</toast>");
// Populate with text and values
doc.SelectSingleNode(L"//text[1]").InnerText(L"Andrew sent you a picture");
doc.SelectSingleNode(L"//text[2]").InnerText(L"Check this out, The Enchantments in Washington!");
// Construct the notification
ToastNotification notif{ doc };
// And send it! Use the AUMID you specified earlier.
ToastNotificationManager::CreateToastNotifier(L"MyPublisher.MyApp").Show(notif);
步驟 4:處理激活
當您點擊通知時,您的 COM 啟動器將會啟動。
More details
AUMID restrictions
AUMID 長度最多應該為 129 個字元。 如果 AUMID 長度超過 129 個字元,排程的通知將無法運作 - 新增排程toast通知時,您會收到下列例外狀況:傳遞至系統呼叫的數據區域太小。(0x8007007A)