【发布时间】: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)
【问题讨论】: