I'm trying to write a program in Python that is aware of when alert boxes/dialogues are shown. It's dealing with multiple monitors, and I want it to display a visualization on the secondary monitor when a taskbar icon flashes, an error/notification pops up, etc.
As far as I can tell, the way to do detect these events is using message hooks, as described here: http://msdn.microsoft.com/en-us/library/ms632589%28v=vs.85%29.aspx
I was even lucky enough to find an example that accesses the SetWindowsHookEx function from Python. (This particular example uses mouse signals, but I can just change the constants to listen for different messages).
http://www.python-forum.org/pythonforum/viewtopic.php?f=2&t=11154
However, the above example does not work. The callback function is never called, regardless of my mouse clicks, and a middle mouse click does not cause the program to exit.
The example is from 2009 (pre windows 7?),though I don't know if that's the issue.
So, my question is, can anybody 1. find out why the code works, or 2. tell me another way to achieve what I'm doing (preferably in Python, though I'll go to other languages if necesarry).
Edit: Is it possible to do what I'm wanting with WMI? I don't know WMI well, but I know that it does have very good Python interface.
解决方案
With the exception of WH_KEYBOARD_LL and WH_MOUSE_LL, the Windows hooks must be implemented in a DLL that Windows injects into each application process. Therefore, you can't simply implement a callback in your program and expect Windows to run it.
I can think of two ways to solve this problem:
Write a DLL in C or C++ that implements the hook procedure and notifies your main program through some form of inter-process communication. Then load this DLL in your main program and pass its module handle and the hook procedure implemented in that DLL to SetWindowsHookEx.
The SetWinEventHook function may give you what you want. WinEvent hooks can be implemented in your main program.