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

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

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

任何帮助赞赏。

你有没有尝试从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 

这里是关于GetKeyState的进一步的文档

其实Ctrl + C有它自己的Ascii代码(这是3)。 像这样的东西适合我:

 import pyHook,pythoncom def OnKeyboardEvent(event): if event.Ascii == 3: print "Hello, you've just pressed ctrl+c!" 

你可以使用下面的代码来观察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() 

使用这个,似乎pyHook返回

 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)