[Python] Attempting to make a Python auto clicker

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I am attempting to make an autoclicker that checks first if the clicker is enabled then if a user is holding down the left mouse button. If the conditions are met, the program would click with a range of delays. The auto clicking should stop once the user releases the left mouse button. The code I currently have is enabling and disabling fine but when I hold down my mouse button I get 1-2 clicks and then it just stops.

    Second issue I have is when using the auto clicker's hotkeys is I have to not be pressing any additional keys to for the hot key to activate. So for example while playing a game I am unable to move around and provide other inputs enableing or disabling the auto clicker.

    If anyone has any fixes for either of these issues I would greatly appreciate any input.

    import ctypes
    import time
    import threading
    import random
    import keyboard

    # Constants for Windows API mouse events
    MOUSEEVENTF_LEFTDOWN = 0x0002
    MOUSEEVENTF_LEFTUP = 0x0004
    VK_LBUTTON = 0x01 # Virtual key code for the left mouse button

    # Windows API functions
    user32 = ctypes.windll.user32

    def click():
    user32.mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    user32.mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)

    def is_left_mouse_button_pressed():
    return user32.GetAsyncKeyState(VK_LBUTTON) & 0x8000 != 0

    # Control variables
    enabled = False # Toggle for enabling/disabling the clicker

    # Hotkeys
    ENABLE_KEY = 'g' # Press 'g' to enable/disable auto-clicking
    EXIT_KEY = '0' # Press '0' to exit

    def clicker():
    while True:
    if enabled: # Only continue clicking if enabled
    while is_left_mouse_button_pressed(): # Check if the left mouse button is pressed
    click()
    time.sleep(random.uniform(0.05, 0.3)) # Randomized delay between clicks
    time.sleep(0.01) # Short delay to prevent high CPU usage when left-click is not held
    else:
    time.sleep(0.01) # Sleep to prevent high CPU usage when disabled

    def toggle_clicking():
    global enabled
    enabled = not enabled # Toggle state
    print(f"Auto-clicker {'enabled' if enabled else 'disabled'}")

    # Start clicking thread
    clicking_thread = threading.Thread(target=clicker, daemon=True)
    clicking_thread.start()

    # Set up hotkeys
    keyboard.add_hotkey(ENABLE_KEY, toggle_clicking, suppress=False) # Press 'g' to toggle auto-clicking

    # Wait for exit key
    keyboard.wait(EXIT_KEY) # Press '0' to exit

    Continue reading...

Compartilhe esta Página