用Python实现自动按键功能的代码示例

在命令行中运行该脚本,当你按下'a'键时,会启动一个自动按键线程,模拟按下Ctrl+X键,然后释放Ctrl键,并每隔0.03秒重复一次。当你按下'ESC'键时,自动按键线程将停止。

import time
import threading
from pynput import keyboard


class AutoKeyPressThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self.stopped = threading.Event()

    def run(self):
        controller = keyboard.Controller()
        while not self.stopped.is_set():
            # 使用更快的方式模拟按键操作
            controller.press(keyboard.Key.ctrl)
            controller.type("x")
            controller.release(keyboard.Key.ctrl)
            time.sleep(0.03)  # 降低延迟时间


def on_press(key):
    global auto_keypress_thread
    # 按下'a'键启动自动按键线程
    if key == keyboard.KeyCode.from_char("a"):
        if not auto_keypress_thread or not auto_keypress_thread.is_alive():
            auto_keypress_thread = AutoKeyPressThread()
            auto_keypress_thread.start()
    # 按下'ESC'键停止自动按键线程
    elif key == keyboard.Key.esc:
        if auto_keypress_thread:
            auto_keypress_thread.stopped.set()


auto_keypress_thread = None

# 启动键盘监听器
listener = keyboard.Listener(on_press=on_press)
listener.start()


# 每秒钟检查自动按键线程状态
def check_thread():
    global auto_keypress_thread
    if auto_keypress_thread and auto_keypress_thread.is_alive():
        print("自动按键正在运行")
        threading.Timer(1, check_thread).start()
    else:
        print("自动按键已停止")


check_thread()

# 等待监听器结束
listener.join()

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值