从其他类型的未打包应用发送本地 Toast 通知

如果要开发非 C# 或C++的未打包应用,则本主题适用于你。

也就是说,如果你 开发打包的应用(请参阅 为打包的 WinUI 3 桌面应用创建新项目),并且你未开发具有外部位置的打包应用(请参阅 通过外部位置打包来授予包标识),并且你的应用不是 C# 或C++。

Toast 通知是应用在用户当前未使用你的应用时可以构造和传送给用户的消息。 本快速入门指导你完成创建、交付和显示 Windows Toast 通知的步骤。 这些快速入门指导使用本地通知,而本地通知是实现起来最简单的通知。

重要

如果要编写 C# 应用,请参阅 C# 文档。 如果要编写C++应用,请参阅 C++ UWPC++ WRL 文档。

步骤 1:在注册表中注册应用

首先需要在注册表中注册应用的信息,包括用于标识应用的唯一 AUMID、应用的显示名称、图标和 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 激活器

即使应用未运行,也可以随时单击通知。 因此,通知激活是通过 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:发送 toast

在 Windows 10 中,你的 Toast 通知内容是使用自适应语言描述的,该语言允许你对通知的外观具有极大的灵活性。 有关详细信息,请参阅 toast 内容文档

我们将从简单的基于文本的通知开始。 构造通知内容(使用通知库),并显示通知!

重要

发送通知时,必须使用之前用的 AUMID,以便通知能显示为来自您的应用。

简单文本通知
// 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 激活器。

更多详细信息

AUMID 限制

AUMID 长度应最多为 129 个字符。 如果 AUMID 长度超过 129 个字符,则计划的 Toast 通知将不起作用 - 添加计划通知时会收到以下异常:传递给系统调用的数据区域太小。(0x8007007A)