Skip to main content

Mouse:高仿真鼠标控制类

Mouse 类提供了对鼠标的高级仿真操作。所有方法均支持 链式调用,并内置了随机偏移和自动 DPI 感知,确保自动化行为既精准且自然。


1. 导入模块

在使用鼠标控制前,请确保已导入硬件核心类:

# 导入鼠标操作类
from ascript.windows.hardware import Mouse

2. 模拟点击 .click()

模拟鼠标点击。支持移动耗时控制、多重点击、长按逻辑路由及随机偏移。

代码块:

Mouse.click(x=None, y=None, clicks=1, interval=0.1, button="primary", move_duration=0.00, duration=0.0, offset=0)

参数详解:

  • x (int): 目标位置横坐标。若为 None,则在当前位置点击。
  • y (int): 目标位置纵坐标。若为 None,则在当前位置点击。
  • clicks (int): 点击次数。默认为 1 次。
  • interval (float): 多次点击之间的间隔时间(秒)。仅在 clicks > 1 时有效。
  • button (str): 触发的鼠标按键。可选: 'left', 'middle', 'right', 'primary', 'secondary'。
  • move_duration (float): 鼠标移动到目标坐标 (x, y) 所需的时间(秒)。
  • duration (float): 按键按下的物理持续时间(秒)。若 > 0,会自动调用 long_press 逻辑。
  • offset (int): 随机偏移半径(像素)。在以 (x, y) 为中心的区域内随机点击。

3. 原子操作

用于在流水线操作中进行原子级的鼠标控制。

📍 移动 .mouse_move()

代码块:

Mouse.mouse_move(x, y, move_duration=0.1, tween=pyautogui.linear)

参数详解:

  • x / y (int): 目标移动位置的横纵坐标。
  • move_duration (float): 移动耗时(秒)。
  • tween (function): 移动路径动画算法。

⚙️ 按下 .mouse_down()

代码块:

Mouse.mouse_down(x=None, y=None, button="primary", move_duration=0.0)

参数详解:

  • x / y (int): 按下按键时的坐标位置。
  • button (str): 指定按下的鼠标按键。
  • move_duration (float): 移动到该坐标的耗时。

⚙️ 抬起 .mouse_up()

代码块:

Mouse.mouse_up(x=None, y=None, button="primary", move_duration=0.0)

参数详解:

  • x / y (int): 松开按键时的坐标位置。
  • button (str): 指定松开的鼠标按键。

4. 流程控制 .wait()

专门用于在链式操作中插入逻辑等待。

代码块:

Mouse.wait(seconds)

参数详解:

  • seconds (float): 链式调用中的逻辑等待时间(秒)。

5. 滚动与拖拽方法

🎡 模拟滚动 .scroll()

代码块:

Mouse.scroll(lines, x=None, y=None, direction="v")

参数详解:

  • lines (int): 滚动的行数。正数向上,负数向下。
  • x / y (int): 执行滚动前鼠标先移动到的位置。
  • direction (str): 滚动方向。"v" 为垂直滚动,"h" 为水平滚动。

🚜 模拟拖拽 .drag()

代码块:

Mouse.drag(to_x, to_y, from_x=None, from_y=None, move_duration=0.5)

参数详解:

  • to_x / to_y (int): 拖拽的目标终点坐标。
  • from_x / from_y (int): 拖拽的起始坐标。若为 None 则从当前位置开始。
  • move_duration (float): 拖拽过程的耗时。

💡 案例演示

from ascript.windows.hardware import Mouse

# 1. 带随机偏移的右键双击
Mouse.click(x=200, y=200, clicks=2, interval=0.2, button="secondary", offset=10)

# 2. 仿真链式操作:移动 -> 等待 -> 点击 -> 滚动
Mouse.mouse_move(100, 100, move_duration=0.5)
.wait(1)
.click()
.scroll(-500)

开发者笔记
  • DPI 感知:底层已自动启用 DPI 感知。你传入的坐标即为屏幕显示的逻辑坐标,无需手动换算。
  • 安全机制:如果程序失控,请迅速将鼠标移动到屏幕的 四个角落之一,程序将强制停止。