PyQT5 键盘模拟/鼠标连点器的实现

近来在玩一个游戏,找不到合适的鼠标连点器,不是有广告就是功能太复杂,自己写了一个,分享出来,如果有需要的可以自行运行研究。

准备工作

Python版本:Python 3.12.3;运行前确保pyQT5已经安装:

pip install PyQt5

程序运行界面:
在这里插入图片描述在这里插入图片描述

程序代码:

通过引入单独的常量和变量文件,并为每个元素增加中文注释来实现界面语句、变量和常量的统一规划。代码:

常量定义文件(constants.py)

# constants.py
# 常量定义文件,用于统一管理系统中的常量

# 界面文本常量
WINDOW_TITLE = "模拟器"  # 窗口标题

# 按键模拟标签
KEY_TAB_TITLE = "按键模拟"
KEY_INTERVAL_LABEL = "按键间隔(秒):"
KEY_TYPE_LABEL = "按键类型:"
KEY_LABEL = "按键:"
KEY_COUNT_LABEL = "按键次数 (适用于多次按键类型):"
KEY_LOG_LABEL = "按键日志:"

# 鼠标模拟标签
MOUSE_TAB_TITLE = "鼠标模拟"
CLICK_INTERVAL_LABEL = "点击间隔(秒):"
CLICK_TYPE_LABEL = "点击类型:"
CLICK_COUNT_LABEL = "点击次数 (适用于多次点击类型):"
MOUSE_POSITION_LABEL = "鼠标位置:"
MOUSE_LOG_LABEL = "鼠标日志:"

# 按钮标签
START_KEY_BUTTON = "开始 (F10)"
STOP_KEY_BUTTON = "停止 (F11)"
START_MOUSE_BUTTON = "开始 (F9)"
STOP_MOUSE_BUTTON = "停止 (F12)"

# 错误消息
ERROR_MESSAGE = "错误: "

变量定义文件(variables.py)

# variables.py
# 变量定义文件,用于统一管理系统中的变量

# 系统状态变量
pressing = False  # 按键模拟状态
clicking = False  # 鼠标模拟状态
mouse_position = None  # 鼠标当前位置

主程序文件(main.py)

# main.py
# 主程序文件,包含程序的主要逻辑

import sys
import ctypes
import threading
import time
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QLabel, QLineEdit, QTabWidget, QComboBox, QTextEdit, QDoubleSpinBox, QSpinBox, QGridLayout
from PyQt5.QtCore import Qt
import keyboard
from pynput import keyboard as pynput_keyboard, mouse as pynput_mouse

import constants  # 导入常量定义文件
import variables  # 导入变量定义文件

class KeyMouseSimulator(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.bind_hotkeys()

    def setup_ui(self):
        self.setWindowTitle(constants.WINDOW_TITLE)  # 设置窗口标题
        
        tab_widget = QTabWidget(self)
        self.setCentralWidget(tab_widget)
        
        self.key_tab = QWidget()
        self.mouse_tab = QWidget()
        
        tab_widget.addTab(self.key_tab, constants.KEY_TAB_TITLE)  # 设置按键模拟标签
        tab_widget.addTab(self.mouse_tab, constants.MOUSE_TAB_TITLE)  # 设置鼠标模拟标签
        
        self.setup_key_tab()
        self.setup_mouse_tab()
        
    def setup_key_tab(self):
        layout = QGridLayout(self.key_tab)

        layout.addWidget(QLabel(constants.KEY_INTERVAL_LABEL), 0, 0)  # 按键间隔标签
        self.key_interval = QDoubleSpinBox()
        self.key_interval.setValue(0.1)
        layout.addWidget(self.key_interval, 0, 1)

        layout.addWidget(QLabel(constants.KEY_TYPE_LABEL), 1, 0)  # 按键类型标签
        self.key_type = QComboBox()
        self.key_type.addItems(["单个按键", "多次按键", "持续按键"])
        self.key_type.currentIndexChanged.connect(self.update_key_type)
        layout.addWidget(self.key_type, 1, 1)

        layout.addWidget(QLabel(constants.KEY_LABEL), 2, 0)  # 按键标签
        self.key = QLineEdit("a")
        layout.addWidget(self.key, 2, 1)
        self.key.focusInEvent = self.start_key_listening
        self.key.focusOutEvent = self.stop_key_listening

        self.key_count_label = QLabel(constants.KEY_COUNT_LABEL)  # 按键次数标签
        self.key_count = QSpinBox()
        self.key_count.setValue(1)

        layout.addWidget(QPushButton(constants.START_KEY_BUTTON, clicked=self.start_pressing), 4, 0)  # 开始按钮
        layout.addWidget(QPushButton(constants.STOP_KEY_BUTTON, clicked=self.stop_pressing), 4, 1)  # 停止按钮

        self.key_log = QTextEdit()
        self.key_log.setReadOnly(True)
        layout.addWidget(self.key_log, 5, 0, 1, 2)

    def setup_mouse_tab(self):
        layout = QGridLayout(self.mouse_tab)

        layout.addWidget(QLabel(constants.CLICK_INTERVAL_LABEL), 0, 0)  # 点击间隔标签
        self.click_interval = QDoubleSpinBox()
        self.click_interval.setValue(0.1)
        layout.addWidget(self.click_interval, 0, 1)

        layout.addWidget(QLabel(constants.CLICK_TYPE_LABEL), 1, 0)  # 点击类型标签
        self.click_type = QComboBox()
        self.click_type.addItems(["单次点击", "多次点击", "持续点击"])
        self.click_type.currentIndexChanged.connect(self.update_click_type)
        layout.addWidget(self.click_type, 1, 1)

        self.click_count_label = QLabel(constants.CLICK_COUNT_LABEL)  # 点击次数标签
        self.click_count = QSpinBox()
        self.click_count.setValue(1)

        layout.addWidget(QPushButton(constants.START_MOUSE_BUTTON, clicked=self.start_clicking), 3, 0)  # 开始按钮
        layout.addWidget(QPushButton(constants.STOP_MOUSE_BUTTON, clicked=self.stop_clicking), 3, 1)  # 停止按钮

        layout.addWidget(QLabel(constants.MOUSE_POSITION_LABEL), 4, 0)  # 鼠标位置标签
        self.mouse_position_var = QLineEdit("未获取")
        self.mouse_position_var.setReadOnly(True)
        layout.addWidget(self.mouse_position_var, 4, 1)

        self.mouse_log = QTextEdit()
        self.mouse_log.setReadOnly(True)
        layout.addWidget(self.mouse_log, 5, 0, 1, 2)

    def bind_hotkeys(self):
        self.key_type.setCurrentIndex(0)
        self.click_type.setCurrentIndex(0)
        keyboard.add_hotkey('F10', self.start_pressing)
        keyboard.add_hotkey('F11', self.stop_pressing)
        keyboard.add_hotkey('F9', self.start_clicking)
        keyboard.add_hotkey('F12', self.stop_clicking)
        keyboard.add_hotkey('F8', self.get_mouse_position)

    def update_key_type(self):
        if self.key_type.currentText() == "多次按键":
            self.key_tab.layout().addWidget(self.key_count_label, 3, 0)
            self.key_tab.layout().addWidget(self.key_count, 3, 1)
        else:
            self.key_tab.layout().removeWidget(self.key_count_label)
            self.key_tab.layout().removeWidget(self.key_count)
            self.key_count_label.setParent(None)
            self.key_count.setParent(None)

    def update_click_type(self):
        if self.click_type.currentText() == "多次点击":
            self.mouse_tab.layout().addWidget(self.click_count_label, 2, 0)
            self.mouse_tab.layout().addWidget(self.click_count, 2, 1)
        else:
            self.mouse_tab.layout().removeWidget(self.click_count_label)
            self.mouse_tab.layout().removeWidget(self.click_count)
            self.click_count_label.setParent(None)
            self.click_count.setParent(None)

    def start_key_listening(self, event):
        self.key_listener = pynput_keyboard.Listener(on_press=self.on_key_press)
        self.key_listener.start()

    def stop_key_listening(self, event):
        if hasattr(self, 'key_listener'):
            self.key_listener.stop()

    def on_key_press(self, key):
        try:
            self.key.setText(key.char)
        except AttributeError:
            self.key.setText(str(key).replace("Key.", ""))
        self.key.setFocus()

    def start_pressing(self):
        if not variables.pressing:
            variables.pressing = True
            threading.Thread(target=self.press_loop).start()
            self.showMinimized()

    def stop_pressing(self):
        variables.pressing = False
        self.log(self.key_log, "按键已停止")

    def press_loop(self):
        key_count = 0
        while variables.pressing:
            try:
                if self.key_type.currentText() == "单个按键":
                    self.perform_key_press()
                    self.stop_pressing()
                    break
                elif self.key_type.currentText() == "多次按键" and key_count < self.key_count.value():
                    self.perform_key_press()
                    key_count += 1
                elif self.key_type.currentText() == "持续按键":
                    self.perform_key_press()
                time.sleep(self.key_interval.value())
            except Exception as e:
                self.log(self.key_log, f"{constants.ERROR_MESSAGE}{e}")
                self.stop_pressing()

    def perform_key_press(self):
        keyboard.press_and_release(self.key.text())
        self.log(self.key_log, f"按键: {self.key.text()}")

    def start_clicking(self):
        if not variables.clicking:
            variables.clicking = True
            threading.Thread(target=self.click_loop).start()
            self.showMinimized()

    def stop_clicking(self):
        variables.clicking = False
        self.log(self.mouse_log, "点击已停止")

    def click_loop(self):
        click_count = 0
        mouse_controller = pynput_mouse.Controller()
        while variables.clicking:
            try:
                if self.click_type.currentText() == "单次点击":
                    self.perform_click(mouse_controller)
                    self.stop_clicking()
                    break
                elif self.click_type.currentText() == "多次点击" and click_count < self.click_count.value():
                    self.perform_click(mouse_controller)
                    click_count += 1
                elif self.click_type.currentText() == "持续点击":
                    self.perform_click(mouse_controller)
                time.sleep(self.click_interval.value())
            except Exception as e:
                self.log(self.mouse_log, f"{constants.ERROR_MESSAGE}{e}")
                self.stop_clicking()

    def perform_click(self, mouse_controller):
        mouse_controller.click(pynput_mouse.Button.left, 1)
        self.log(self.mouse_log, "鼠标点击")

    def get_mouse_position(self):
        mouse_controller = pynput_mouse.Controller()
        position = mouse_controller.position
        self.mouse_position_var.setText(f"{position[0]}, {position[1]}")
        self.log(self.mouse_log, f"鼠标位置: {position}")

    def log(self, log_display, message):
        log_display.append(message + '\n')
        log_display.verticalScrollBar().setValue(log_display.verticalScrollBar().maximum())

def main():
    # 提高程序优先级
    ctypes.windll.kernel32.SetPriorityClass(ctypes.windll.kernel32.GetCurrentProcess(), 0x00000080)  # HIGH_PRIORITY_CLASS

    app = QApplication(sys.argv)
    
    window = KeyMouseSimulator()
    window.show()
    
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

说明:

  1. 常量定义文件(constants.py):用于统一管理所有的字符串常量和文本常量,每个常量都附有中文注释解释其用途。
  2. 变量定义文件(variables.py):用于统一管理所有的变量状态,如按键和点击状态。
  3. 主程序文件(main.py):主程序逻辑被清晰地组织在这里,并且引用了常量和变量文件中的内容。每个函数都有详细的中文注释,解释其功能。

通过这种方式,所有的界面语句、变量和常量都得到了统一的管理,便于后期的维护和扩展。
详细内容后期在InsCode中会发布出来。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
PyQt5的Model/View是一种用于创建用户界面的框架。它基于MVC(Model-View-Controller)设计模式,提供了一种将数据和界面分离的方法。 Model/View框架中,Model负责管理和提供数据,View负责数据的可视化展示,而两者之间由Controller进行交互。 在PyQt5中,Model通常是QAbstractItemModel类或其子类的实例。它提供了一种标准的接口,用于管理和操作数据。通过Model,我们可以对数据进行添加、删除和修改等操作,并在这些操作之后通知View进行更新。 View则是用户界面上的部件,如QTreeView、QTableView或QListView等。它负责将Model中的数据以视觉化的方式展示给用户,并根据用户的操作与Model进行交互。View会通过信号与槽机制、或直接获取Model的数据来更新界面。 在Model/View框架中,Model和View之间是通过索引(Index)进行连接的。索引是一个由Model提供的标识,用于标记数据的位置和层级关系。View在显示数据时,会根据索引来获取数据的值,并根据需要进行格式化或呈现。 通过Model/View框架,我们可以实现数据和界面的解耦合,通过更改Model中的数据来自动更新界面。同时,Model/View也提供了一些方便的方法和信号,用于处理数据的排序、过滤和选择等操作。 总而言之,PyQt5的Model/View是一种用于创建用户界面的框架,可以通过数据模型和视图来管理和展示数据。它可以使用户界面更加直观、灵活和易于维护。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个爱折腾的小人物

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值