如何用C语言创建Windows任务栏弹窗通知?Shell_NotifyIcon使用异常
实现Windows 10兼容的通知弹窗
Windows 10及后续版本中,Shell_NotifyIcon的传统气球通知功能确实被系统限制(默认仅在用户交互托盘图标时显示,无法主动弹出),若要实现类似目标截图的弹窗效果,有两种可行方案:
方案一:修复Shell_NotifyIcon的气球通知配置
若坚持使用托盘图标关联的通知,需补充NIF_INFO相关参数配置,具体修正代码如下:
NOTIFYICONDATAA dataa; ZeroMemory(&dataa, sizeof(dataa)); // 初始化结构体,避免未定义行为 dataa.cbSize = sizeof(NOTIFYICONDATAA); dataa.hWnd = hWnd; dataa.uID = 0; // 添加NIF_INFO标识以启用气球通知 dataa.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE | NIF_INFO; dataa.hIcon = LoadIcon(NULL, IDI_QUESTION); strcpy(dataa.szTip, "Test1"); // 填充气球通知的标题、内容和图标类型 strcpy(dataa.szInfoTitle, "通知标题"); strcpy(dataa.szInfo, "这是测试通知内容"); dataa.dwInfoFlags = NIIF_INFO; // 指定通知使用信息类图标 // 添加托盘图标 Shell_NotifyIcon(NIM_ADD, &dataa); // 触发通知显示 Shell_NotifyIcon(NIM_MODIFY, &dataa);
注意:Windows 10 1607版本后,这类气球通知默认仅在用户悬停或点击托盘图标时显示,无法主动弹出到桌面,系统优先级较低。
方案二:使用Windows 10+原生Toast通知
要实现主动弹出的桌面通知,推荐使用系统原生Toast通知(与目标截图风格一致),需借助Windows Runtime API实现,示例代码如下(C++/WinRT):
#include <winrt/Windows.UI.Notifications.h> #include <winrt/Windows.Data.Xml.Dom.h> using namespace winrt; using namespace Windows::UI::Notifications; using namespace Windows::Data::Xml::Dom; void ShowToastNotification() { // 构造Toast通知的XML模板 XmlDocument toastXml; toastXml.LoadXml(L"<toast><visual><binding template='ToastGeneric'><text>通知标题</text><text>这是测试Toast通知内容</text></binding></visual></toast>"); // 创建并发送Toast通知 ToastNotification toast(toastXml); ToastNotificationManager::CreateToastNotifier(L"你的应用标识").Show(toast); }
额外说明
- Toast通知需要确保系统通知设置中允许当前应用发送通知
- 桌面应用使用Toast通知时,若未打包为Appx,需配置通知扩展或使用桌面桥工具适配
- Toast通知会出现在系统通知中心,支持点击交互,更符合现代Windows的交互逻辑
内容的提问来源于stack exchange,提问作者Erz
相关产品推荐
相关产品推荐

