Python check if Left Mouse Button is being held?

4k Views Asked by At

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

3

There are 3 best solutions below

3
Strive Sun On BEST ANSWER

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
1
Anshuman Komawar On

Check if win32api.GetAsyncKeyState(0x01) < 0 in the if condition.

0
Dom On

I made it work with mouse5!

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

def ac():
    if keystate < 0:
        mouse.click(Button.left, 1)
        time.sleep(0.1)
    else:
        pass

while True:
    keystate = win32api.GetAsyncKeyState(0x06)
    ac()