如何通过微软官方方式查询Windows Do Not Disturb模式状态?
问题:查询Windows专注助手(请勿打扰)模式状态的官方方式
我正在开发一款向Windows设备用户发送通知的应用,目前通过调用SHQueryUserNotificationState接口查询通知状态,以此判断是否可弹出通知。该接口在演示模式或Teams会议场景下可正常工作,但当用户开启Windows**专注助手(请勿打扰)**模式时,仍返回QUNS_ACCEPTS_NOTIFICATIONS。此前类似方案已不再支持或从未被支持,请问微软是否提供官方方式查询该模式的状态?
当前使用的代码示例
C++代码
bool CheckNotificationState() { QUERY_USER_NOTIFICATION_STATE notificationState = QUNS_ACCEPTS_NOTIFICATIONS; HRESULT hr = S_OK; if (g_bCheckNotificationState){ LogInfo("Checking Notification State"); hr = SHQueryUserNotificationState(¬ificationState); if (hr != S_OK || notificationState != QUNS_ACCEPTS_NOTIFICATIONS) { LogInfo("User not accepting notifications"); return false; } } return true; }
PowerShell代码
$winClass = Add-Type -MemberDefinition ' [DllImport("shell32.dll")] public static extern int SHQueryUserNotificationState(out int state); ' -Name WinClass -PassThru $state = [int]0 $null = $WinClass::SHQueryUserNotificationState([ref]$state) write-host "state: $state"
官方解决方案
微软提供了UserNotificationListener API(Windows Runtime API体系)来查询专注助手(请勿打扰)状态,这是目前官方推荐的标准方式,支持Windows 10 1903及以上版本。
核心逻辑
通过UserNotificationListener.Current.GetNotificationSettingAsync()方法可获取当前通知权限状态:
NotificationSetting.Enabled:允许发送通知NotificationSetting.DisabledForFocusAssist:明确处于专注助手(请勿打扰)模式
C++示例代码
#include <winrt/Windows.UI.Notifications.h> #include <winrt/Windows.Foundation.h> using namespace winrt; using namespace Windows::UI::Notifications; using namespace Windows::Foundation; IAsyncAction CheckFocusAssistState() { UserNotificationListener listener = UserNotificationListener::Current; NotificationSetting setting = co_await listener.GetNotificationSettingAsync(); if (setting == NotificationSetting::DisabledForFocusAssist) { LogInfo("Focus Assist (Do Not Disturb) is active"); // 此时不应发送通知 } else if (setting == NotificationSetting::Enabled) { LogInfo("Notifications are allowed"); // 可正常发送通知 } }
注意事项
- 需在应用清单中声明
userNotificationListener功能; - 首次调用时需引导用户授权应用访问通知监听权限;
- 若需兼容Windows 10 1903之前的系统,可结合
SHQueryUserNotificationState做降级逻辑处理。
内容的提问来源于stack exchange,提问作者Thomas A. Bosler
相关产品推荐
相关产品推荐

