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

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

import time
import threading
from pynput import keyboardclass 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_threadif auto_keypress_thread and auto_keypress_thread.is_alive():print("自动按键正在运行")threading.Timer(1, check_thread).start()else:print("自动按键已停止")check_thread()# 等待监听器结束
listener.join()


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部