社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用python创建输入文本的热键

Derek • 5 年前 • 1589 次点击  

我遵循了一些其他教程,并能够创建一个应用程序,打印“检测到的热键”时,永远移+P是在键盘上输入。下面是我使用的.pY代码。它只打印我运行.exe时打开的命令窗口中的文本。我希望能得到一些在我的光标位置输入文本的东西。我正在使用Python3.7

例如,我希望热键shift+p能够在我用不和谐、松弛或gmail聊天时输入文本。这可能吗?还是有更好的方法来做这样的事情?

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()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43703
 
1589 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Headcrab
Reply   •   1 楼
Headcrab    6 年前

这是一个很小的修改,做了你想要的,花了我大约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键。