使用pyhook来响应组合键(不只是单击键)?

rec*_*ner 10 python windows keyboard automation keyboard-shortcuts

我一直在环顾四周,但我找不到如何使用pyhook来响应键组合的示例,例如Ctrl+,C而很容易找到如何响应单个按键的示例,如单独CtrlC单独按键.

顺便说一下,我在谈论Windows XP上的Python 2.6.

任何帮助赞赏.

Rod*_*Rod 9

您是否尝试过使用HookManager中的GetKeyState方法?我没有测试过代码,但它应该是这样的:

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
Run Code Online (Sandbox Code Playgroud)

以下是有关GetKeyState的进一步文档

  • 并且GetKeyState似乎不存在. (3认同)
  • 我认为它已被转移到`pyHook.GetKeyState` (2认同)

Hug*_*ell 7

您可以使用以下代码来查看pyHook返回的内容:

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()
Run Code Online (Sandbox Code Playgroud)

使用它,似乎pyHook返回

c:      Ascii 99, KeyID 67,  ScanCode 46
ctrl:   Ascii 0,  KeyID 162, ScanCode 29
ctrl+c: Ascii 3,  KeyID 67,  ScanCode 46
Run Code Online (Sandbox Code Playgroud)

(Python 2.7.1,Windows 7,pyHook 1.5.1)


小智 7

实际上Ctrl + C拥有自己的Ascii代码(即3).这样的东西适合我:

import pyHook,pythoncom

def OnKeyboardEvent(event):
    if event.Ascii == 3:
        print "Hello, you've just pressed ctrl+c!"
Run Code Online (Sandbox Code Playgroud)