Python 检查是否按住鼠标左键?

Python check if Left Mouse Button is being held?

我是 Python 的新手,我想制作一种自动点击器,当我按住鼠标左键时,它会每 0.1 秒持续点击一次。 我的问题是,当我 运行 我的脚本时,我的鼠标立即开始点击。我该怎么办?:

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

谢谢

检查if条件是否为win32api.GetAsyncKeyState(0x01) < 0

我的问题是,当我 运行 我的脚本时,我的鼠标立即开始点击。我该怎么办?

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.

您应该改用 win32api.GetAsyncKeyState(0x01)&0x8000

现在,它唯一能做的就是点击一次,这让我的点击变成了双击。

因为GetAsyncKeyState检测鼠标左键的按键状态。当按下鼠标左键时,会调用click函数,click会实现鼠标左键按下和松开这两个动作。然后在while循环的地方,GetAsyncKeyState会检测释放动作,这就是双击后停止的原因。

建议你设置鼠标左键启动,鼠标右键停止

代码示例:

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

我让它与 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()