首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 在 Windows 10 操作中心顯示 Toast 通知實作指南

     編輯:程式設計綜合問答

核心概念

Windows 10「操作中心」通知本質上是 Toast 通知,演進自舊版「氣泡提示」。C++/C# 均可透過 Windows Runtime (WinRT) API 或 Desktop Bridge 發送。

C++ 實作方案(WinRT + C++/WinRT)

1. 專案設定

  • Visual Studio 2019/2022 → 專案屬性 → C/C++ → General → Consume Windows Runtime Extension → Yes (/ZW)。
  • 安裝 NuGet 套件:Microsoft.Windows.CppWinRT、Microsoft.Windows.SDK.Contracts。

2. 定義 Toast XML 內容

<toast>
  <visual>
    <binding template="ToastGeneric">
      <text>標題:新訊息</text>
      <text>內容:您有一則新通知</text>
      <image placement="appLogoOverride" src="ms-appx:///Assets/Logo.png"/>
    </binding>
  </visual>
  <actions>
    <action content="查看" arguments="action=view"/>
    <action content="忽略" arguments="action=dismiss"/>
  </actions>
</toast>

3. 發送程式碼

#include 
#using namespace winrt::Windows::UI::Notifications;
#using namespace winrt::Windows::Data::Xml::Dom;

void SendToast() {
    // 載入 XML
    XmlDocument doc;
    doc.LoadXml(LR"(...XML內容...)");

    // 建立通知器
    ToastNotifier notifier = ToastNotificationManager::CreateToastNotifier();
    ToastNotification toast(doc);
    
    // 可選:設定過期時間、標籤、群組
    toast.ExpirationTime(chrono::hours(1));
    toast.Tag(L"my_tag");
    toast.Group(L"my_group");

    // 發送
    notifier.Show(toast);
}

C# 實作方案(UWP API in Desktop)

using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;

public void ShowToast(string title, string body) {
    string xml = $@"
        {title}{body}";
    
    var doc = new XmlDocument();
    doc.LoadXml(xml);
    var notifier = ToastNotificationManager.CreateToastNotifier();
    notifier.Show(new ToastNotification(doc));
}

需在 Package.appxmanifest 宣告 uap:ToastCapable,或使用 MSIX 封裝 / Desktop Bridge 取得應用身分識別。

傳統氣泡提示 (NotifyIcon) 替代方案

若不想打包 MSIX,可沿用 Shell_NotifyIcon + NIF_INFO 顯示系統托盤氣泡,但不會進入操作中心歷史記錄,且 Windows 11 已棄用。

關鍵檢查清單

  • ☐ 應用有有效的 AppUserModelId (AUMID)(MSIX/捷徑安裝自動產生)。
  • ☐ 通知 XML 符合 Toast Schema。
  • ☐ 系統設定 → 通知與動作 → 你的應用「通知」開關開啟。
  • ☐ 測試 ToastNotificationManager.History.Clear() 避免殘留影響除錯。

現代 Windows 通知請走 WinRT Toast API,C++ 使用 C++/WinRT,C# 直接引用 UWP 命名空間,並確保應用有正確身分識別(MSIX/捷徑)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved