如何在Python中收听Windows 10通知



我的Python测试脚本导致我们的产品引发Windows通知("Toast"(。我的python脚本如何验证是否确实引发了通知?

我发现使用Windows.UI.Notifications.Management.UserNotificationListener(ref(在C#中制作通知侦听器是可能的,我也发现使用win10toast在Python中制作自己的通知-但我如何收听其他应用程序的通知?

您可以使用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)   

在谷歌上搜索python windows notification listener只会得到这个不错的结果,但它并不完整。

由于我找不到任何关于如何做到这一点的独立示例,这里有一个完全可用的代码:

from winrt.windows.ui.notifications.management import UserNotificationListener
from winrt.windows.ui.notifications import KnownNotificationBindings
def handler(asd, aasd):
unotification = asd.get_notification(aasd.user_notification_id)
# print(dir(unotification))
if hasattr(unotification, "app_info"):
print("App Name: ", unotification.app_info.display_info.display_name)
text_sequence = unotification.notification.visual.get_binding(KnownNotificationBindings.get_toast_generic()).get_text_elements()
it = iter(text_sequence)
print("Notification title: ", it.current.text)
while True:
next(it, None)
if it.has_current:
print(it.current.text)
else:
break            
else:
pass
listener = UserNotificationListener.get_current()
listener.add_notification_changed(handler)
while True: pass

在windows 10和winrt v1.0.2103.1 上测试

最新更新