【问题标题】:On Windows, how can I install the lowest level global keyboard hook possible?在 Windows 上,如何安装最低级别的全局键盘挂钩?
【发布时间】:2011-09-14 11:19:28
【问题描述】:

我正在 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

【问题讨论】:

标签: python windows hook


【解决方案1】:

您绝对应该从 user32 中查看 SetWindowsHookEx。这些函数允许您注册全局键盘挂钩。 (只是不要忘记通过调用 CallNextHookEx 传递它们。)

链接:http://msdn.microsoft.com/en-us/library/ms644990(v=vs.85).aspx

我不知道如何从 python 中做到这一点,抱歉。

【讨论】:

  • 我也试过了——它似乎和热键有同样的问题。 :(
【解决方案2】:

您是否尝试过在 SourceForge 上使用 pyHook?您可以查看DaniWeb 的用法示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    相关资源
    最近更新 更多