【问题标题】:Python - win32api cursor script that automatically moves a cursor, clicks and brings it backPython - win32api 光标脚本,自动移动光标,点击并返回
【发布时间】:2021-03-09 03:16:23
【问题描述】:

我有一个检测鼠标点击的脚本。我需要它:[1。将光标移动到位置 2. 单击该位置 3. 将其移回原始位置],只要我单击屏幕上的任何位置,它就会运行。问题是,脚本创建的点击仍然被注册并创建一个来回循环。我怎样才能改变这种行为,所以当点击从脚本而不是我发生时它不会运行该函数?

import win32api
import time

state_left = win32api.GetAsyncKeyState(0x01)  # LMB down is 0 or 1, LMB up is -127 or -128

time.sleep(2)
while True:
    a = win32api.GetAsyncKeyState(0x01)
    if a != state_left:
        state_left = a
        print(a)
        if a < 0:
            print('Left Button Pressed')
        else:
            print('Left Button Released')```

【问题讨论】:

    标签: python-3.x winapi pyautogui


    【解决方案1】:

    根据document,可以使用GetAsyncKeyState

    GetAsyncKeyState 函数适用于鼠标按钮。但是,它会检查物理鼠标按钮的状态,而不是物理按钮映射到的逻辑鼠标按钮。例如,调用 GetAsyncKeyState(VK_LBUTTON) 始终返回物理鼠标左键的状态,无论它是映射到逻辑鼠标左键还是逻辑鼠标右键。您可以通过调用 GetSystemMetrics(SM_SWAPBUTTON) 确定系统当前物理鼠标按钮到逻辑鼠标按钮的映射。

    因此,只有在鼠标物理状态发生变化时才会触发,才能使程序正常工作。

    两次触发的原因是a的值设置错误。只需通过GetAsyncKeyState函数获取鼠标状态的最高位即可,如下代码所示:

    c = 1
    state_left = win32api.GetAsyncKeyState(0x01)  # LMB down is 0 or 1, LMB up is -127 or -128
    
    while True:
        a = win32api.GetAsyncKeyState(0x01) & 0x8000
        if a != state_left:
            state_left = a
            print(a)
            if a != 0:
                print('Left Button Pressed')
            else:
                print('Left Button Released')
                before = win32api.GetCursorPos()
                win32api.SetCursorPos((1300, 900))
    
                pyautogui.click()
                win32api.SetCursorPos(before)
    
        time.sleep(0.001)
    

    更多参考:What are these numbers in the code GetAsyncKeyState(VK_SHIFT) & 0x8000 ? Are they essential?

    【讨论】:

    • 感谢您的回答。我改变了它,但现在“按下鼠标按钮”被打印了两次(并且只有一次在释放时),并且鼠标仍在来回移动。请告诉我我做错了什么。我编辑了上面的代码
    • @DarioVuksan 我已经更新了我的答案,你可以参考一下。
    • 经过print(bin(a)) 的一些测试后,我理解了这个函数的行为。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多