[Writing game auxiliary tools using Python] Part 3: Implementation of mouse combo

image.png

Foreword

Here is the third article of [Writing Game Auxiliary Tools in Python]: Implementation of Mouse Combo. This article mainly introduces the use of Python to implement the mouse combo function.

A mouse combo is multiple clicks of a mouse button, usually the left mouse button, within a short period of time. When a mouse combo is triggered, the mouse button is quickly pressed and released multiple times, creating a continuous click effect.

The main uses of mouse combos here are:

  • Help us with mouse clicks and crazy combos;
  • For example, if you fire continuously in a shooting game, if you click to attack the monster, you can attack the monster continuously and frequently;
  • Through mouse combos, you can quickly perform multiple actions and improve operating efficiency.

Overview of the context of the article

The process and functions of this article are shown in the figure below:

  • Combined with the keyboard monitoring of the previous article to realize a freely retractable mouse combo function;

  • Use keyboard monitoring events to drive some operations (the keyboard monitoring function is mainly used in conjunction with the subsequent mouse combo);

    • When pressing Ctrl + Shift + A, perform mouse combo (keyboard key combinations can be customized)
    • When pressing Ctrl + Shift + Q, Stop combo (the keyboard key combination can be customized)





























































































Auxiliary tools









Mouse combo









Keyboard monitoring









Start a combo









Ctrl + Shift + A









Ctrl + Shift + Q









stop combo







Mouse combos are often used for quick actions in games or certain applications, such as continuous fire in shooters. Through mouse combos, you can quickly perform multiple actions and improve operating efficiency.

Context of the series of articles

The content of the series of articles is generally as follows, and new articles may be updated in the future.

  • Click directly to:[Using Python to write game auxiliary tools] Part 1: Overview

  • Click directly to: [Using Python to write game auxiliary tools] Part 2: Application of keyboard monitoring< /strong>

  • Click directly to: [Using Python to write game auxiliary tools] Part 3: Mouse combo Realize

  • Click directly to: [Using Python to write game auxiliary tools] Part 4: Windows window operations strong>

  • Click directly to: [Using Python to write game auxiliary tools] Part 5: Creating interactive game tools Interface: PySide6/PyQT efficiently builds GUI tools

Knowledge points

Libraries and modules Description
ctypes External functions used to call dynamic link libraries (DLLs) and shared libraries in Python (here used for mouse clicks)

According to the official website, ctypes is an external function library for Python. It provides C-compatible data types and allows calling functions in a DLL or shared library. You can use this module to wrap these libraries in pure Python.

Regarding the steps for calling the ctypes function (for specific operations, please refer to the official documentation):

  1. First, import the ctypes module.
  2. Define the parameter type and return value type of the function, which can be set through the argtypes and restype attributes.
  3. Use ctypes.windll to access the Windows dynamic link library and get the required functions.
  4. Call the function and pass the appropriate parameters.

This module can implement the theme of this article very well.

Mouse combo implementation

In Python programming, use the SendInput function in the ctypes library. By calling the SendInput function multiple times to send mouse press and release events, the effect of mouse combos can be simulated.

It should be noted that the frequency and number of mouse clicks may be limited by the operating system or application. Some applications may have their own click rate limits, or the operating system may limit the frequency of mouse clicks to avoid abuse or misuse.

Code

# encoding=utf-8

import time
import ctypes

#Define mouse event constants
MOUSE_EVENT_LEFT_DOWN = 0x0002
MOUSE_EVENT_LEFT_UP = 0x0004


#Define mouse input structure
class MouseInput(ctypes.Structure):
    _fields_ = [("dx", ctypes.c_long),
                ("dy", ctypes.c_long),
                ("mouseData", ctypes.c_ulong),
                ("dwFlags", ctypes.c_ulong),
                ("time", ctypes.c_ulong),
                ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong))]


#Define input structure
class Input(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = [("mi", MouseInput)]

    _anonymous_ = ("_input",)
    _fields_ = [("type", ctypes.c_ulong),
                ("_input", _INPUT)]


#Define the parameter type of SendInput function
SendInput = ctypes.windll.user32.SendInput
SendInput.argtypes = (ctypes.c_uint, ctypes.POINTER(Input), ctypes.c_int)
SendInput.restype = ctypes.c_uint


#Define mouse click function
def click_mouse(count: int = 10):
    """Simulate mouse click events"""
    
    for i in range(count):
        #Create a left mouse button press event
        mouse_down = Input()
        mouse_down.type = 0
        mouse_down.mi.dwFlags = MOUSE_EVENT_LEFT_DOWN

        #Create a left mouse button release event
        mouse_up = Input()
        mouse_up.type = 0
        mouse_up.mi.dwFlags = MOUSE_EVENT_LEFT_UP

        #Pack the event into an input structure array
        events = (Input * 2)()
        events[0] = mouse_down
        events[1] = mouse_up

        #Send input event
        SendInput(2, events, ctypes.sizeof(Input))
        # Pause
        time.sleep(0.01)


if __name__ == '__main__':
    click_mouse(count=100)

Code explanation

  • MOUSE_EVENT_LEFT_DOWN and MOUSE_EVENT_LEFT_UP are constants representing the press and release of the left mouse button;
  • MouseInput is a structure used to describe mouse event information, including mouse coordinates, mouse data, flags, time and additional information, etc.;
  • Input is a structure used to describe input event information, including event type and event specific information. The union _INPUT is used here to contain mouse input information;
  • SendInput is a function in the Windows User32 library that sends input events. Here, we use the ctypes library to set up the function call and specify the parameter type and return value type;
  • The click_mouse function is used to simulate mouse click events. It accepts an optional list of random pause times as a parameter to control the interval between clicks. First create mouse press and release events and pack them into an input structure array. Then use the SendInput function to send the input event and pause for a period of time through the time.sleep function.

In this code, we set the parameter type and return value type of the SendInput function, and use ctypes.windll.user32.SendInput to access the Windows User32 library code>SendInput function. Then the SendInput function is called directly in the click_mouse function to send the input event.

Operating effect

After running the code, you can see 100 rapid mouse clicks. This implements the mouse combo.

Mouse click demo.gif

Keyboard monitoring starts mouse combo

In this part, combining the keyboard monitoring of the previous article and the mouse combo code above, we can implement a function to control mouse combos through shortcut keys.

The advantage of using shortcut keys to operate is that it can be retracted and released freely.

Code

# encoding=utf-8

import time
import ctypes
import keyboard
import threading

#Define mouse event constants
MOUSE_EVENT_LEFT_DOWN = 0x0002
MOUSE_EVENT_LEFT_UP = 0x0004


#Define mouse input structure
class MouseInput(ctypes.Structure):
    _fields_ = [("dx", ctypes.c_long),
                ("dy", ctypes.c_long),
                ("mouseData", ctypes.c_ulong),
                ("dwFlags", ctypes.c_ulong),
                ("time", ctypes.c_ulong),
                ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong))]


#Define input structure
class Input(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = [("mi", MouseInput)]

    _anonymous_ = ("_input",)
    _fields_ = [("type", ctypes.c_ulong),
                ("_input", _INPUT)]


#Define the parameter type of SendInput function
SendInput = ctypes.windll.user32.SendInput
SendInput.argtypes = (ctypes.c_uint, ctypes.POINTER(Input), ctypes.c_int)
SendInput.restype = ctypes.c_uint

flag=False


#Define mouse click function
def click_mouse():
    """Simulate mouse click events"""
    while flag:
        #Create a left mouse button press event
        mouse_down = Input()
        mouse_down.type = 0
        mouse_down.mi.dwFlags = MOUSE_EVENT_LEFT_DOWN

        #Create a left mouse button release event
        mouse_up = Input()
        mouse_up.type = 0
        mouse_up.mi.dwFlags = MOUSE_EVENT_LEFT_UP

        #Pack the event into an input structure array
        events = (Input * 2)()
        events[0] = mouse_down
        events[1] = mouse_up

        #Send input event
        SendInput(2, events, ctypes.sizeof(Input))
        # Pause
        time.sleep(0.01)


def start_keyboard_listener():
    """
    Callback function to start keyboard monitoring
    """
    global flag
    flag = True
    print("Ctrl + Shift + A pressed")
    threading.Thread(target=click_mouse).start()


def stop_keyboard_listener():
    """
    Callback function to stop keyboard monitoring
    """
    global flag
    flag=False
    print("Ctrl + Shift + Q pressed")


if __name__ == '__main__':
    # Register hotkeys and set callback functions
    keyboard.add_hotkey('ctrl + shift + a', start_keyboard_listener)
    keyboard.add_hotkey('ctrl + shift + q', stop_keyboard_listener)
    # Enter the listening state
    keyboard.wait()

Code explanation

This code implements the monitoring function of starting and stopping mouse clicks through hotkeys.

  • The click_mouse() function defines the mouse click operation, and the specific implementation is in the code you provided previously.

  • The start_keyboard_listener() function is a callback function that starts keyboard listening. This function is triggered when the hotkey “Ctrl + Shift + A” is pressed. It will set a global variable flag to True, then create a new thread and call the click_mouse() function in this thread, thus Realize the combo effect of mouse clicks.

  • The stop_keyboard_listener() function is a callback function to stop keyboard listening. This function is triggered when the hotkey “Ctrl + Shift + Q” is pressed. It will set the global variable flag to False, thus stopping the combo effect of mouse clicks.

  • In the __main__ section, two hotkeys are registered through keyboard.add_hotkey, corresponding to the callback functions for starting and stopping keyboard monitoring respectively. Then call keyboard.wait() to enter the listening state and wait for the hotkey to be triggered.

Generally speaking, this code implements the combo effect of controlling mouse clicks through hotkeys. Press “Ctrl + Shift + A” to start a combo, press “Ctrl + Shift + Q” to stop a combo.

Operating effect

As you can see, it is very smooth, and it is very easy to control mouse combos and can be retracted and retracted freely.

  • When pressing Ctrl + Shift + A, perform mouse combo (the keyboard key combinations can be customized)
  • When pressing Ctrl + Shift + Q, Stop combo (the keyboard key combination can be customized)

Keyboard monitoring mouse combos.gif

Summary

This article introduces the basic use of the ctypes module, and uses ctypes to implement mouse combo operations.

Finally, combined with the previous Keyboard monitoring article, the retractable and retractable mouse combo function was realized.

This article summarizes the use of the ctypes module to implement mouse combo operations.

  • First, the basic usage of the ctypes module is introduced, which can be used to call functions in the dynamic link library;
  • Then, use the ctypes module to call the mouse event function in the Windows API to implement the function of simulating mouse press and release;
  • Finally, combined with the previous keyboard monitoring article, the mouse combo function is bound to keyboard events to realize the function of triggering combos based on key presses. Finally, a complete sample code is given, demonstrating how to use the ctypes module and the keyboard listening function to implement a flexible mouse combo.

By studying this article, readers can learn how to use the ctypes module to implement mouse combos and combine it with the keyboard monitoring function for more advanced operations. This is useful for automated tasks or gaming operations that require a lot of mouse clicks. Readers can further expand and optimize the code according to their own needs to meet the requirements of actual application scenarios.

syntaxbug.com © 2021 All Rights Reserved.