I've been looking around but I can't find an example of how to use pyhook to respond to key combinations such as Ctrl + C whereas it is easy to find examples of how to respond to single keypresses such as Ctrl or C separately.
BTW, I'm talking about Python 2.6 on Windows XP.
Any help appreciated.
Have you tried to use the GetKeyState method from HookManager? I haven't tested the code but it should be something like this:
from pyHook import HookManager
from pyHook.HookManager import HookConstants
def OnKeyboardEvent(event):
ctrl_pressed = HookManager.GetKeyState(HookConstants.VKeyToID('VK_CONTROL') >> 15)
if ctrl_pressed and HookConstant.IDToName(event.keyId) == 'c':
# process ctrl-c
Here is further documentation on GetKeyState
You can use the following code to watch what pyHook returns:
import pyHook
import pygame
def OnKeyboardEvent(event):
print 'MessageName:',event.MessageName
print 'Ascii:', repr(event.Ascii), repr(chr(event.Ascii))
print 'Key:', repr(event.Key)
print 'KeyID:', repr(event.KeyID)
print 'ScanCode:', repr(event.ScanCode)
print '---'
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
# initialize pygame and start the game loop
pygame.init()
while True:
pygame.event.pump()
using this, it appears that pyHook returns
c: Ascii 99, KeyID 67, ScanCode 46
ctrl: Ascii 0, KeyID 162, ScanCode 29
ctrl+c: Ascii 3, KeyID 67, ScanCode 46
(Python 2.7.1, Windows 7, pyHook 1.5.1)
Actually Ctrl+C have it's own Ascii code (which is 3). Something like this works for me:
import pyHook,pythoncom
def OnKeyboardEvent(event):
if event.Ascii == 3:
print "Hello, you've just pressed ctrl+c!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With