Python检测和移动鼠标

2024-06-17 08:45:02 发布

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

所以,我正在用鼠标制作一个脚本,当LMB和RMB都被点击时,鼠标会向下移动一定量。我遇到的问题是当我尝试移动鼠标时。我一放入win32api行,第一次打印后命令提示符就会冻结。我曾尝试使用其他一些python库来实现这一点,要么导致相同的问题,要么根本不工作(因为应用程序是全屏的)。如果您对win32api行进行了注释,它将在按下两个按钮的持续时间内打印

如果可能的话,我想解决冻结问题

图书馆:

  • 皮奥图吉
  • win32api
  • 老鼠
  • 平普特
  • pydirectinput
while True:
  if win32api.GetAsyncKeyState(1) < 0 and win32api.GetAsyncKeyState(2) < 0:
    print("Both pressed")
    win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, 0, 1, 0 ,0)
    print("this never gets printed")

Tags: 脚本应用程序图书馆鼠标按钮持续时间print老鼠
1条回答
网友
1楼 · 发布于 2024-06-17 08:45:02

这似乎有效:

import keyboard  # using module keyboard
import win32api
import win32con

def move(x,y):
    if win32api.GetAsyncKeyState(1) < 0 and win32api.GetAsyncKeyState(2) < 0:
        print("Both pressed")
        win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, x, y, 0 ,0)
        print("moved")
    else:
        return

if __name__ == "__main__":
    while True:  # making a loop
        move(0, 500)
        try:  # used try so that if user pressed other than the given key error will not be shown
            if keyboard.is_pressed('q'):  # if key 'q' is pressed 
                print('You Pressed A Key!')
                break  # finishing the loop
        except Exception as ex:
            print(ex)
            break

或者选中此选项,每次移动鼠标1个像素:

import keyboard  # using module keyboard
import win32api
import win32con
import time

def move(x,y):
    if x is None or x == 0:
        x = 0
    if y is None or y == 0:
        y = 1
    if win32api.GetAsyncKeyState(1) < 0 and win32api.GetAsyncKeyState(2) < 0:
        print("Both pressed")
        win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, x, y, 0 ,0)  # | win32con.MOUSEEVENTF_ABSOLUTE
        print("moved")
    else:
        return

if __name__ == "__main__":
    while True:  # making a loop
        move(0, 0)
        #time.sleep(1)
        try:  # used try so that if user pressed other than the given key error will not be shown
            if keyboard.is_pressed('q'):  # if key 'q' is pressed 
                print('You Pressed A Key!')
                break  # finishing the loop
        except Exception as ex:
            print(ex)
            break

    

相关问题 更多 >