繁体   English   中英

使用python ctypes检测Shift键

[英]Detect shift-key presses with python ctypes

我想检测在执行python脚本期间是否按下CTRL | SHIFT | ALT来更改其行为。 所以对于ex,如果我在按住SHIFT的情况下运行脚本,我希望GUI弹出而不是命令行...等等。

由于msvcrt.kbhit无法检测到SHIFT键,因此我进行了一些挖掘,发现此解决方案似乎很有希望。 我将SHIFT添加到其热键列表中作为测试。 不幸的是,如果您在dos外壳中尝试下面的代码,您会看到它可以正确检测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)

有一个名为PyHook的软件包,它负责与Windows输入事件有关的最底层细节。 可能值得一看。

链接到键盘挂钩文档:

链接到安装程序:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM