Using pyhook to respond to key combination (not ju

2019-01-22 15:41发布

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.

4条回答
Luminary・发光体
2楼-- · 2019-01-22 15:52

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)

查看更多
可以哭但决不认输i
3楼-- · 2019-01-22 15:55

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!"
查看更多
疯言疯语
4楼-- · 2019-01-22 15:57

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

查看更多
看我几分像从前
5楼-- · 2019-01-22 16:03

I didn't have luck with any of the other answers, so this is what I took to doing

class Keystroke_Watcher:
    def __init__(self, master):
        self.hm = HookManager()
        self.hm.KeyDown = self.on_key_down
        self.hm.KeyUp = self.on_key_up
        self.hm.HookKeyboard()
        self.keys_held = set()  # set of all keys currently being pressed

    def get_key_combo_code(self):
        # find some way of encoding the presses.
        return '+'.join([HookConstants.IDToName(key) for key in self.keys_held])

    def on_key_down(self, event):
        try:
            self.keys_held.add(event.KeyID)
        finally:
            return True

    def on_key_up(self, event):
        keycombo = self.get_key_combo_code()
        print(keycombo)
        try:
            # Do whatever you want with your keycombo here
        finally:
            self.keys_held.remove(event.KeyID)
            return True

    def shutdown(self):
        PostQuitMessage(0)
        self.hm.UnhookKeyboard()
查看更多
登录 后发表回答