使用python ctypes检测Shift键 [英] Detect shift-key presses with python ctypes

查看:95
本文介绍了使用python ctypes检测Shift键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to detect if CTRL|SHIFT|ALT are held down during the execution of a python script to alter its behavior. So for ex if i run a script with SHIFT held down i want a GUI to pop open instead of a command line... etc...

因为msvcrt.kbhit无法检测到SHIFT按键,我做了一些挖掘,发现此解决方案,这似乎很有希望。我将SHIFT添加到其热键列表中作为测试。不幸的是,如果您在dos外壳中尝试下面的代码,您会看到它可以正确检测ESC和NUMLOCK按键,但是它无法捕获SHIFT按键,而且我不知道为什么。

since msvcrt.kbhit couldn't detect SHIFT key presses i did some digging and found this solution which seemed very promising. I added SHIFT to its hotkey list as a test. Unfortunately if you try the code below in a dos shell you'll see that it correctly detects ESC and NUMLOCK key presses, but it won't catch SHIFT presses and i can't figure why that is.

任何见识将不胜感激。

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输入事件有关的大多数底层细节。

There's a package named PyHook, that takes care of most low-level details related to input events on windows. It may be worth looking at.

链接到键盘挂钩文档:

  • https://sourceforge.net/apps/mediawiki/pyhook/index.php?title=PyHook_Tutorial#Keyboard_Hooks

安装程序链接:

  • http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32
  • http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook

这篇关于使用python ctypes检测Shift键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆