'How can I listen to Windows 10 notifications in Python?

My Python test script causes our product to raise Windows notifications ("Toasts"). How can my python script verify that the notifications are indeed raised?

I see it's possible to make a notification listener in C# using Windows.UI.Notifications.Management.UserNotificationListener (ref), And I see I can make my own notifications in Python using win10toast - but how do I listen to othe apps' notifications?



Solution 1:[1]

You can use pywinrt to archive the same thing in python. A basic example would look something like this:

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()

notifications = await listener.get_notifications_async(NotificationKinds.TOAST)
    

Subscribing to NotificationChanged (listener.add_notification_changed(handler)) appears to be broken in the python package unfortunately.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vincent