在Windows上,如何安装最低级别的全局键盘钩子?
我正在Windows上用Python制作一个自定义的街机启动器。我想选择系统和游戏,然后启动模拟器,并且需要一个特定的按键组合来关闭模拟器。我的按键监听在测试随机应用程序时都能正常工作,但当我真正启动模拟器(比如Nestopia)时,我的按键监听就失效了。目前我在使用RegisterHotKey,它能接收到事件,但无法捕捉到热键。有没有人知道怎么才能在Nestopia之前安装一些东西,以便真正捕捉到事件?这是我的代码:
import ctypes
import win32con
from ctypes import wintypes
from ctypes import byref
user32 = ctypes.windll.user32
class SimpleKeyboardHook:
def getNextId(self):
SimpleKeyboardHook._id += 1
return SimpleKeyboardHook._id
# modifiers is a bitmask with win32con.[MOD_SHIFT, MOD_ALT, MOD_CONTROL, MOD_WIN]
def waitFor(self, key, modifiers):
# coerce to 0 if necessary
modifiers = modifiers or 0
id = self.getNextId()
hk = user32.RegisterHotKey(None, id, modifiers, key)
print "register hotkey: ",hk
if not hk:
print "Unable to register hotkey for key ", key
return False
print "registered id", id
try:
msg = wintypes.MSG()
while user32.GetMessageA(byref(msg), None, 0, 0) != 0:
print "got message",msg.message,"which is not",win32con.WM_HOTKEY
if msg.message == win32con.WM_HOTKEY:
print "got hotkey"
if msg.wParam == id:
print "found proper hotkey"
return True
user32.TranslateMessage(byref(msg))
user32.DispatchMessageA(byref(msg))
finally:
user32.UnregisterHotKey(None, id)
return False
SimpleKeyboardHook._id = 0
2 个回答
1
你应该看看user32里的SetWindowsHookEx这个函数。这些函数可以让你注册全局的键盘钩子。(只要记得通过调用CallNextHookEx来传递它们。)
链接:http://msdn.microsoft.com/en-us/library/ms644990(v=vs.85).aspx
不过,我不知道怎么用Python来实现这个,抱歉。