首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使pynput防止某些击键到达特定应用程序?

如何使pynput防止某些击键到达特定应用程序?
EN

Stack Overflow用户
提问于 2020-07-11 20:37:22
回答 1查看 367关注 0票数 0

我想要创建一个工具,允许我在不支持它的应用程序(斯克里韦纳)中使用一些Vim样式的命令。

例如,如果

  • 当前模式是Command模式和
  • 用户按w按钮,

然后,插入符号应该向右移动一个字符。Scrivener应该接收“右箭头”信号,而不是w字符。

为了实现这一点,我编写了以下代码(基于以下两个答案:12):

代码语言:javascript
复制
from pynput.keyboard import Key, Listener, Controller
from typing import Optional
from ctypes import wintypes, windll, create_unicode_buffer

def getForegroundWindowTitle() -> Optional[str]:
    hWnd = windll.user32.GetForegroundWindow()
    length = windll.user32.GetWindowTextLengthW(hWnd)
    buf = create_unicode_buffer(length + 1)
    windll.user32.GetWindowTextW(hWnd, buf, length + 1)
    if buf.value:
        return buf.value
    else:
        return None

class State:
    def __init__(self):
        self.mode = "Command"

state = State()
keyboard = Controller()

def on_press(key):
    pass

def on_release(key):
    if key == Key.f12:
        return False
    window_title = getForegroundWindowTitle()
    if not window_title.endswith("Scrivener"):
        return
    print("Mode: " + state.mode)
    print('{0} release'.format(
        key))
    if state.mode == "Command":
        print("1")
        if str(key) == "'w'":
            print("2")
            print("w released in command mode")
            # Press the backspace button to delete the w letter
            keyboard.press(Key.backspace)
            # Press the right arrow button
            keyboard.press(Key.right)
    if key == Key.insert:
        if state.mode == "Command":
            state.mode = "Insert"
        else:
            state.mode = "Command"

# Collect events until released
print("Press F12 to exit")

with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

每当我在命令模式下按下Scrivener中的w按钮时,就会向Scrivener发送两次击键:

  1. 删除已键入的w字符的后退空间。
  2. 右箭头移动插入符号。

这是可行的,但是您可以看到w字符再次被显示和删除(参见这段视频)。

如果模式是w,而当前的焦点窗口是Scrivener应用程序,那么如何确保使用Scrivener的按键没有到达Scrivener呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-13 08:46:46

首先,您需要安装pyHook和pywin32库。

然后通过py钩子监控键盘信息。如果需要截获键盘信息(例如,按w),则返回False。

最后,通过pythoncom.PumpMessages ()实现循环监控。以下是样本:

代码语言:javascript
复制
import pyHook
import pythoncom
from pynput.keyboard import Key, Listener, Controller
keyboard = Controller()
def onKeyboardEvent(event):
    if event.Key == "F12":
        exit()
    print("1")
    if event.Key == 'W':
        print("2")
        print("w released in command mode")
        # Press the right arrow button
        keyboard.press(Key.right)
        return False

    print("hook" + event.Key)
    return True

# Collect events until released
print("Press F12 to exit")
hm = pyHook.HookManager()
hm.KeyDown = onKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages() 
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62854319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档