Python ctypes: SetWindowsHookEx callback function never called

旧城冷巷雨未停 提交于 2019-12-12 12:33:58

问题


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.


回答1:


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:

  1. 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.

  2. The SetWinEventHook function may give you what you want. WinEvent hooks can be implemented in your main program.



来源:https://stackoverflow.com/questions/6458812/python-ctypes-setwindowshookex-callback-function-never-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!