Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pyhook to respond to key combination (not just single keystrokes)?

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.

like image 200
reckoner Avatar asked Jan 03 '11 02:01

reckoner


3 Answers

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

like image 74
Rod Avatar answered Oct 20 '22 11:10

Rod


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)

like image 28
Hugh Bothwell Avatar answered Oct 20 '22 11:10

Hugh Bothwell


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!"
like image 45
Anon Avatar answered Oct 20 '22 11:10

Anon