wxPython: Catching key events globally

There's something I'm trying to do with wxPython and I can't figure out how. (I'm on Windows 7 and I'm okay with a Windows-only solution.)

I want to catch key events globally. This means key-up, key-down and char events. (I'm trying to build something like AHK in Python.)

Now, I know wxPython allows global hotkeys, but that's not satisfactory, because I want to get all the events, including key up, key down and char. How can I do that?

I tried using pyHook, which almost worked except char events aren't implemented. Char events seem to be tricky and I want to know how to capture them globally. (ie in all apps.) I'm also okay with solutions that use other tools except wxPython. (Except not a separate GUI framework, I'm happy with using wxPython for the GUI, just tools for capturing the char events.)


Sorry, but you can't catch WM_CHAR events directly from a Python executable. You will need to write a native Windows DLL to hook WH_GETMESSAGE and then separately notify your Python process that a key was pressed.

As you can see here the way to catch WM_CHAR is to catch the events read by GetMessage() using the WH_GETMESSAGE hook. Sadly, any global hook for that message must be able to run in the context of any process and so has to be implemented as a DLL (as mandated by the API docs). That means you cannot do this inside your Python process. This is also covered in the Python win32 archives here.

That means you need to write a native DLL to hook the messages and then use your favourite form of IPC (eg Post a message to another window) to pass any interesting events to your Python process.

If you really just want Python bindings for AutoHotKey, you could use pyahk to do this for you.


The free and open source screen reader for Windows, NVDA, implements this functionality. Perhaps take a look at how they accomplish it?

Source: winInputHook.py


PyWin32 has SetWindowsHook which might work according to this thread. You might be able to use ctypes, although I haven't found any good examples as of yet.

I also found this project which looks promising:

  • https://pypi.python.org/pypi/PyUserInput
  • 链接地址: http://www.djcxy.com/p/87114.html

    上一篇: 限制节点数

    下一篇: wxPython:捕捉全球关键事件