【问题标题】:How to read keypresses in the background in python如何在python的后台读取按键
【发布时间】:2016-05-18 16:15:03
【问题描述】:

我知道在后台处理它是一件非常困难的事情,但我正在寻找的是一个记录按键的程序,以及按键之间需要多少时间。我所调查的内容都无法在后台记录或实际工作。

编辑:

import win32con, ctypes, ctypes.wintypes

def esc_pressed():
    print("Hotkey hit!")

ctypes.windll.user32.RegisterHotKey(None, 1, 0, 0xDD) # this binds the ']' key

try:
    msg = ctypes.wintypes.MSG()
    ctypes.windll.user32.GetMessageA
    while ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
        if msg.message == win32con.WM_HOTKEY:
            esc_pressed()
        ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
        ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg))
finally:
    ctypes.windll.user32.UnregisterHotKey(None, 1)

这允许程序在后台运行,但它使用您绑定的输入字符,而不是拾取它。我仍然需要确保输入的字符到达焦点所在的窗口。

【问题讨论】:

  • @ValentinLorentz,对不起,它在后台对我不起作用。查看绑定,但它们将输入从焦点窗口中移开
  • 你不能只用一个线程吗?
  • @ValentinLorentz 我一直在研究它,但对我来说没有任何意义的东西实际上有效或可以格式化为 while 循环

标签: python-3.x keypress


【解决方案1】:

您可能必须抓住按键,然后再次模拟相同的按键操作。尝试检查 Python 键盘模块。

编辑:添加代码示例。

import keyboard, time

def KeyPressSample(startkey='tab', endkey='esc'):
    while True:  # making a inifinte loop
        try:
            if keyboard.is_pressed(startkey):
                time.sleep(0.25)
                print("%s Key pressed." % startkey)
            elif keyboard.is_pressed(endkey):
                print("%s Key pressed." % endkey)
                break
        except KeyboardInterrupt:
            print('\nDone Reading input. Keyboard Interupt.')
            break
        except Exception as e:
            print(e)
            break

【讨论】:

  • 改善答案的一个想法可能是添加代码 sn-ps 建模您将如何使用 python 键盘模块来完成此类任务:)
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 2021-11-13
  • 2013-03-03
  • 1970-01-01
  • 2018-04-06
相关资源
最近更新 更多