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

2024-04-24 16:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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

谢谢


Tags: fromimport脚本trueiftimebutton鼠标
3条回答

我用鼠标5成功了

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()

检查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

相关问题 更多 >