如何创建一个自动化按键和鼠标点击工具

在日常计算机使用中,我们常常需要进行重复性的操作,例如定时按下某个键盘按键或模拟鼠标点击。这可能涉及到玩游戏、自动化测试、数据录入等各种场景。为了实现这些功能,你可以创建一个自动化按键和鼠标点击工具。本教程将介绍如何使用Python和一些库来创建这样的工具。

1. 开场故事

想象一下,你正在玩一个需要不断点击鼠标的游戏,或者你需要在浏览器上定期执行某项任务。每次都手动点击或按下键盘按键是多么繁琐和乏味!那么,有没有一种方法可以自动化这些操作,让计算机来代劳呢?答案是肯定的,本文将向你展示如何创建一个自动化按键和鼠标点击的工具,让你告别重复性操作的困扰。

2. 准备工作

在开始之前,我们需要准备一些工具和库。首先,你需要安装Python,如果你还没有安装,可以从官方网站下载并安装。接下来,我们将使用以下库:

  • PyQt5:用于创建图形用户界面。
  • pynput:用于监听键盘和鼠标事件。
  • pygetwindow:用于获取当前活动窗口的信息。
  • pyautogui:用于模拟键盘按键和鼠标点击事件。

你可以使用以下命令安装这些库:

pip install PyQt5 pynput pygetwindow pyautogui

3. 创建图形用户界面

首先,我们将创建一个图形用户界面(GUI),以便用户可以轻松地控制自动化工具。我们将使用PyQt5库来构建GUI。以下是一个示例GUI的代码:

from PyQt5 import QtWidgets, uic
from PyQt5.QtGui import QPainter, QColor, QCursor
from PyQt5.QtCore import Qt, QRectF
from pynput.mouse import Button, Controller
import pyautogui
import threading
import time
import os

# ... 其他代码 ...

class Ui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi(ui_path, self)

        # ... 创建GUI元素 ...

        self.show()

# ... 其他代码 ...

在这个GUI中,我们可以添加按键、设置时间间隔、监控按键状态等功能。

4. 监听键盘和鼠标事件

接下来,我们将创建一个用于监听键盘和鼠标事件的类。我们使用pynput库来实现这一功能。以下是一个示例代码片段:

from pynput import keyboard, mouse
import pygetwindow as gw

class Controller:
    def __init__(self):
        self.mouse_controller = mouse.Controller()
        self.mouse_pressed = False
        self.keyboard_stop_flag = True
        self.mouse_auto_stop_flag = True

    def on_press(self, key):
        try:
            # 检查游戏是否运行并且是当前活动窗口
            # game_windows = gw.getWindowsWithTitle(self.game_title)
            # if game_windows and gw.getActiveWindow() in game_windows:
            if key == keyboard.Key.f1:
                if self.keyboard_stop_flag:
                    self.keyboard_stop_flag = False
                    window.statusButton.setChecked(True)
                    self.start_keyboard_press_key()
                else:
                    self.keyboard_stop_flag = True
                    window.statusButton.setChecked(False)
            elif key == keyboard.Key.f2:
                # 鼠标连点
                if self.mouse_auto_stop_flag:
                    self.mouse_auto_stop_flag = False
                    window.mouseStatusButton.setChecked(True)
                    self.start_mouse_auto_click_key(self.MOUSE_STATUS_CLICK)
                else:
                    self.mouse_auto_stop_flag = True
                    window.mouseStatusButton.setChecked(False)
            elif key == keyboard.Key.f3:
                # 鼠标长按
                if self.mouse_auto_stop_flag:
                    self.mouse_auto_stop_flag = False
                    window.mouseStatusButton.setChecked(True)
                    self.start_mouse_auto_click_key(self.MOUSE_STATUS_PRESS)
                else:
                    self.mouse_auto_stop_flag = True
                    window.mouseStatusButton.setChecked(False)
            elif key == keyboard.Key.f4:
                # 按键映射
                pass
            elif key == keyboard.Key.f12:
                mouse_pos = QCursor.pos()
                global mouseX, mouseY
                mouseX = mouse_pos.x()
                mouseY = mouse_pos.y()
                window.xPos.setText(str(mouseX))
                window.yPos.setText(str(mouseY))
            else:
                print(f"{key} pressed")
        except Exception as e:
            import traceback
            traceback.print_exc()

    # ... 其他代码 ...

在这个类中,我们定义了一个Controller类,用于监听键盘和鼠标事件。根据按键的不同,我们可以执行不同的操作,例如启动键盘按键模拟、鼠标点击等。

5. 创建自动化操作

现在,我们可以创建自动化的操作,例如模拟键盘按键和鼠标点击。以下是示例代码:

class Controller:
    # ... 其他代码 ...

    def start_keyboard_press_key(self):
        for key, interval in key_time_dict.items():
            if key in pyautogui.KEYBOARD_KEYS:
                print("启动线程, 按键: ", key, " 间隔: ", interval)
                t = threading.Thread(target=self.press_key, args=(key, interval))
                t.daemon = True
                t.start()
            else:
                print(f"Key: {key} is not a valid key")

    def press_key(self, key, interval):
        print("按键: ", key, " 间隔: ", interval)
        while True:
            if self.keyboard_stop_flag:
                break
            pyautogui.press(key)
            time.sleep(interval)

    def start_mouse_auto_click_key(self, status):
        print("启动鼠标自动点击线程... ")
        if status == self.MOUSE_STATUS_CLICK:
            print(f"鼠标自动点击... delay:{window.mouseDelay.value()}")
            delay = window.mouseDelay

.value()
            t = threading.Thread(target=self.mouse_click, args=(delay,))
            t.daemon = True
            t.start()
        elif status == self.MOUSE_STATUS_PRESS:
            print("鼠标长按... ")
            mouseC = mouse.Controller()
            pyautogui.mouseDown()
            t = threading.Thread(target=self.mouse_press)
            t.daemon = True
            t.start()

    def mouse_click(self, interval):
        print("鼠标自动点击, 间隔: ", interval)
        while True:
            if self.mouse_auto_stop_flag:
                break
            # 获取鼠标当前位置
            print("指定的坐标... {}, {}".format(mouseX, mouseY))
            if mouseX == 0 and mouseY == 0:
                mouseXx, mouseYy = pyautogui.position()
            else:
                mouseXx = mouseX
                mouseYy = mouseY
            pyautogui.click(int(mouseXx), int(mouseYy))
            time.sleep(interval)

    def mouse_press(self):
        print("开启鼠标长按... ")
        while True:
            if self.mouse_auto_stop_flag:
                # 释放鼠标左键并退出循环
                pyautogui.mouseUp()
                print("鼠标长按结束")
                break
            print("鼠标长按中... ")
            time.sleep(0.3)

这个部分的代码用于启动键盘按键模拟和鼠标点击操作。根据用户的设置,它可以实现自动点击、长按和模拟按键等功能。

6. 启动监听器

最后,我们需要启动监听器来监控键盘和鼠标事件。我们在主程序中创建了一个start_listener函数,该函数启动了监听键盘和鼠标事件的线程。以下是示例代码:

def start_listener():
    game_title = "Your Game Title"  # 替换为你的游戏窗口标题
    global controller
    controller = Controller()
    # 启动一个守护线程
    print("启动线程监听...")
    daemon = threading.Thread(target=keyboard_listener, args=(controller,))
    daemon.daemon = True
    daemon.start()
    daemon = threading.Thread(target=mouse_listener, args=(controller,))
    daemon.daemon = True
    daemon.start()

def keyboard_listener(args):
    print("启动线程监听键盘...")
    controller = args
    with keyboard.Listener(
            on_press=controller.on_press,
            on_release=controller.on_release) as listener:
        listener.join()

def mouse_listener(args):
    print("启动线程监听鼠标...")
    controller = args
    with mouse.Listener(
            on_click=controller.on_mouse_press,
            on_release=controller.on_mouse_release) as listener:
        listener.join()

通过这些代码,我们可以启动监听器来监控键盘和鼠标事件,然后根据用户的设置执行相应的自动化操作。

7. 总结

通过创建一个自动化按键和鼠标点击工具,你可以轻松地执行重复性的操作,提高工作效率。这个工具可以用于各种应用场景,包括游戏、自动化测试、数据录入等。希望本教程对你有所帮助,让你更好地掌握自动化操作的技巧。

声明:本站所有文章,如无特殊说明或标注,均为本站(王大神)原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
指数词

解锁ChatGPT Plus:绕开OpenAI限制的全新方式

2023-9-13 19:15:50

指数词

Linux Kernel 6.5发布:初步支持Wi-Fi 7和USB4

2023-9-13 19:39:47

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索