【问题标题】:Detect shift-key presses with python ctypes使用 python ctypes 检测 shift 键按下
【发布时间】:2014-02-14 07:38:20
【问题描述】:

我想检测在执行 python 脚本期间是否按住 CTRL|SHIFT|ALT 以改变其行为。因此,例如,如果我在按住 SHIFT 的情况下运行脚本,我希望弹出一个 GUI 而不是命令行...等等...

由于 msvcrt.kbhit 无法检测到 SHIFT 按键,我进行了一些挖掘,发现了这个 solution,这似乎很有希望。我将 SHIFT 添加到其热键列表中作为测试。不幸的是,如果您在 dos shell 中尝试下面的代码,您会发现它正确检测到 ESC 和 NUMLOCK 按键,但它不会捕捉到 SHIFT 按键,我不知道为什么会这样。

任何见解将不胜感激。

import ctypes, ctypes.wintypes
import win32con

# Register hotkeys
ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_ESCAPE)
ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_NUMLOCK)
ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_LSHIFT)
ctypes.windll.user32.RegisterHotKey(None, 1, 0, win32con.VK_RSHIFT)

# Loop until one of the hotkeys are pressed
try:
    msg = ctypes.wintypes.MSG()
    while ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
        if msg.message == win32con.WM_HOTKEY:
            print("KEY PRESSED!")

        ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
        ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg))

# Cleanup
finally:
    ctypes.windll.user32.UnregisterHotKey(None, 1)

【问题讨论】:

    标签: python winapi ctypes


    【解决方案1】:

    有一个名为PyHook 的包,它负责处理与Windows 上的输入事件相关的大多数低级细节。可能值得一看。

    到键盘挂钩文档的链接:

    安装程序链接:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 2018-02-15
      • 2016-09-30
      相关资源
      最近更新 更多