开发者

On Windows, how can I install the lowest level global keyboard hook possible?

开发者 https://www.devze.com 2023-03-13 00:26 出处:网络
I\'m working on a custom arcade launcher in python on Windows.I want to choose system and game, then launch the emulator - and require a certain key combination to kill the emulator.All of my key hook

I'm working on a custom arcade launcher in python on Windows. I want to choose system and game, then launch the emulator - and require a certain key combination to kill the emulator. All of my key hooks work when testing with random applications, but when I actually launch the emulators (e.g. Nestopia), my key hooks fail to fire. I am currently using RegisterHotKey, which gets events but not the hotkeys. Anyone have an idea how to install something low enough to actually get the event before Nestopia? Here's my code:

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:
      开发者_StackOverflow  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


You should definitely look at SetWindowsHookEx from user32. These functions allow you to register global keyboard hooks. (Just don't forget to pass them on by calling CallNextHookEx.)

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

I have no idea how to do that from python though, sorry.


Have you tried using pyHook over on SourceForge yet? You can check DaniWeb for example usage.

0

精彩评论

暂无评论...
验证码 换一张
取 消