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

用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()

相关推荐