如何使用 Python 收听 Windows 10 通知?

Jon*_*han 9 python notifications windows-10

我的 Python 测试脚本使我们的产品引发 Windows 通知(“Toasts”)。我的 python 脚本如何验证通知是否确实发出?

我发现可以使用Windows.UI.Notifications.Management.UserNotificationListener( ref ) 在 C# 中创建通知侦听器,并且我发现我可以使用win10toast在 Python 中创建自己的通知- 但如何侦听其他应用程序的通知?

Vin*_*ent 3

您可以使用pywinrt访问python 中的绑定。一个基本的例子看起来像这样:

from winrt.windows.ui.notifications.management import UserNotificationListener, UserNotificationListenerAccessStatus
from winrt.windows.ui.notifications import NotificationKinds, KnownNotificationBindings

if not ApiInformation.is_type_present("Windows.UI.Notifications.Management.UserNotificationListener"):
    print("UserNotificationListener is not supported on this device.")
    exit()

listener = UserNotificationListener.get_current()
accessStatus = await listener.request_access_async()

if accessStatus != UserNotificationListenerAccessStatus.ALLOWED:
    print("Access to UserNotificationListener is not allowed.")
    exit()

def handler(listener, event):
    notification = listener.get_notification(event.user_notification_id)

    # get some app info if available
    if hasattr(notification, "app_info"):
        print("App Name: ", notification.app_info.display_info.display_name)

listener.add_notification_changed(handler)   
Run Code Online (Sandbox Code Playgroud)