我一直在寻找,但我找不到如何使用pyhook来响应组合的示例,例如 Ctrl + C < / kbd>虽然很容易找到如何单独响应单个按键的示例,例如 Ctrl 或 C 。
BTW,我在谈论Windows XP上的Python 2.6。
任何帮助表示感谢。
答案 0 :(得分: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
答案 1 :(得分:7)
实际上Ctrl + C拥有自己的Ascii代码(即3)。这样的事情对我有用:
import pyHook,pythoncom
def OnKeyboardEvent(event):
if event.Ascii == 3:
print "Hello, you've just pressed ctrl+c!"
答案 2 :(得分:6)
您可以使用以下代码来观察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)
答案 3 :(得分:0)
我没有任何其他答案的运气,所以这就是我做的事情
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()