Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. (i.e. 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.)

like image 978
Ram Rachum Avatar asked Jul 26 '15 19:07

Ram Rachum


1 Answers

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 (e.g. 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.

like image 115
Peter Brittain Avatar answered Sep 23 '22 20:09

Peter Brittain