我遵循了其他一些教程,并且能够创建在键盘上输入Shift + P时打印“ Detected HotKey”的应用程序。下面是我正在使用的.py代码。它仅在我运行.exe时打开的命令窗口中打印文本。我希望能够得到一些在光标位置输入文本的东西。我正在使用python 3.7
例如,当我在Discord,Slack或Gmail中聊天时,我希望热键Shift + P能够输入文本。这可能吗?还是有更好的方法来做这样的事情?
from pynput import keyboard
COMBINATIONS = [
{keyboard.Key.shift, keyboard.KeyCode(char="p")},
{keyboard.Key.shift, keyboard.KeyCode(char="P")}
]
current = set()
def execute():
print("Dectected HotKey")
def on_press(key):
if any ([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
答案 0 :(得分:0)
这是一个需要您做的小修改,我花了2分钟阅读pynput
文档:
from pynput import keyboard
from pynput.keyboard import Key, Controller
kbd = Controller()
COMBINATIONS = [
{keyboard.Key.shift, keyboard.KeyCode(char="p")},
{keyboard.Key.shift, keyboard.KeyCode(char="P")}
]
current = set()
def execute():
print("Dectected HotKey") #goes into the console window
#"hitting" backspace to remove the "P",
#must be unnecessary if we use some other modifier (Alt, Ctrl)
kbd.press(Key.backspace)
kbd.release(Key.backspace)
kbd.type('Hi motherfucker!') #goes into the active app window
def on_press(key):
if any ([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
并且文本将大写,因为在输入“ Shift”时您仍将按住Shift。