卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章1829本站已运行4109

Python 模拟用户操作鼠标

传入坐标x、y直接调用就行了
import pyautogui,win32gui
 
鼠标_单击_模拟用户(坐标x,坐标y)
 
def 鼠标_单击_模拟用户(x, y, 窗口句柄=None, action=1):
    ' 模拟用户点击鼠标\n\n 窗口句柄可以不填 action=1表示左键单击,action=2表示双击'
    original_pos = pyautogui.position()
    try:
        if 窗口句柄:
            try:
                win32gui.SetForegroundWindow(窗口句柄)
            except Exception as e:
                print(f"无法设置窗口句柄({窗口句柄})为前台窗口:", e)
                return False
 
            x_screen, y_screen = win32gui.ClientToScreen(窗口句柄, (x, y))
            print(f"客户区坐标转屏幕坐标:({x}, {y}) -> ({x_screen}, {y_screen})")
 
        # 映射鼠标操作
        operations = {
            1: lambda: pyautogui.click(x_screen, y_screen),
            2: lambda: pyautogui.doubleClick(x_screen, y_screen),
            3: lambda: pyautogui.mouseDown(x=x_screen, y=y_screen, button='left'),
            4: lambda: pyautogui.mouseUp(x=x_screen, y=y_screen, button='left')
        }
 
        # 获取对应的鼠标操作
        operation = operations.get(action)
        if not operation:
            print(f"无效的鼠标操作: {action}")
            return False
 
        # 执行对应的鼠标操作
        operation()
        print(f"执行了鼠标操作: {action} 在 ({x_screen}, {y_screen})")
 
    except Exception as e:
        print("无法执行鼠标操作,出现异常:", e)
        return False
    finally:
        # 恢复鼠标位置
        pyautogui.moveTo(*original_pos)
 
    return True
 
卓越飞翔博客
上一篇: Java安全 CC链1分析
下一篇: Python 鼠标循环自动点击
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏