pythonwinapimouseclick-eventpynputonmouseclick

Python check if Left Mouse Button is being held?


I'm pretty new to Python and I'd like to make a kind of an Autoclicker, which keeps clicking every 0.1 seconds when my left mouse button is held down. My Problem is, that when I run my script, my mouse instantly starts clicking. What should I do?:

import win32api
import time
from pynput.mouse import Button, Controller
mouse = Controller()

while True:

    if win32api.GetAsyncKeyState(0x01):
        mouse.click(Button.left, 1)
        time.sleep(0.1)
    else:
        pass

Thanks


Solution

  • My Problem is, that when I run my script, my mouse instantly starts clicking. What should I do?

    If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState.

    You should use win32api.GetAsyncKeyState(0x01)&0x8000 instead.

    Now, the only thing it does is click once, which makes my click a double click.

    Because GetAsyncKeyState detects the key state of the left mouse button. When you press the left mouse button, the click function is called, click will realize the two actions of the left mouse button press and release. Then in the place of the while loop, GetAsyncKeyState will detect the release action, which is why it stops after double-clicking.

    I suggest you set the left mouse button to start and the right mouse button to stop.

    Code Sample:

    import win32api
    import time
    from pynput.mouse import Button, Controller
    mouse = Controller()
    
    while True:
    
        if (win32api.GetAsyncKeyState(0x01)&0x8000 > 0):
            flag = True
            while flag == True:
                   mouse.click(Button.left, 1)
                   time.sleep(0.1)
                   if (win32api.GetAsyncKeyState(0x02)&0x8000 > 0):
                       flag = False
        else:
            pass