我想要创建一个工具,允许我在不支持它的应用程序(斯克里韦纳)中使用一些Vim样式的命令。
例如,如果
Command模式和w按钮,然后,插入符号应该向右移动一个字符。Scrivener应该接收“右箭头”信号,而不是w字符。
为了实现这一点,我编写了以下代码(基于以下两个答案:1、2):
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发送两次击键:
w字符的后退空间。这是可行的,但是您可以看到w字符再次被显示和删除(参见这段视频)。
如果模式是w,而当前的焦点窗口是Scrivener应用程序,那么如何确保使用Scrivener的按键没有到达Scrivener呢?
发布于 2020-07-13 08:46:46
首先,您需要安装pyHook和pywin32库。
然后通过py钩子监控键盘信息。如果需要截获键盘信息(例如,按w),则返回False。
最后,通过pythoncom.PumpMessages ()实现循环监控。以下是样本:
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() https://stackoverflow.com/questions/62854319
复制相似问题