Block pyhook from so-generated keystrokes?

I use pyhook and pyhk to match keystrokes on a Windows XP computer, and it works fine unless a keystroke (e.g. ctrl + z) already exists in the application. In this case, ctrl + z goes to the application and launches the action that was associated with it.

If you are familiar with autohotkey , note that autohotkey circumvents this by defining hotkeys that can be passed to the main application. Here are some codes that fall into this idea. Please note that I am trying to track when the ctrl key is not working.

  import pythoncom, pyHook control_down = False def OnKeyboardEvent_up(event): global control_down if event.Key=='Lcontrol' or event.Key=='Rcontrol': control_down=False return True def OnKeyboardEvent(event,action=None,key='Z',context=None): global control_down if event.Key=='Lcontrol' or event.Key=='Rcontrol': control_down=True if control_down and event.Key==key: print 'do something' return False if event.Key=='Pause': win32gui.PostQuitMessage(1) return False # return True to pass the event to other handlers return True if __name__ == '__main__': hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.KeyUp = OnKeyboardEvent_up hm.HookKeyboard() # set the hook pythoncom.PumpMessages() # wait forever 

Any help was appreciated.

Thanks!

+4
source share
2 answers

If you are only interested in Windows, you can use the win API, for example. via ctypes:

 >>> from ctypes import windll >>> windll.user32.RegisterHotKey(0, -1, 0x0002, 0x5a) 

After running these lines of code Ctrl (code = 0x0002), the combination + Z (code = 0x5a) no longer works in Python REPL.

So, you better see which windows are registered hotkeys. You will find more information on MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646309(v=vs.85).aspx

+2
source

I can be completely mistaken here, but from my understanding of the pyHook documentation, to prevent keystrokes from clicking on another application, you need to change return True to def OnKeyboardEvent_up(event): and OnKeyboardEvent(event,action=None,key='Z',context=None): on return False (or anything else but True .

0
source

All Articles