使用win32api如何降低鼠标移动速度?
实现Win32API鼠标缓慢移动的解决方案
方法一:用SetCursorPos实现平滑慢移(推荐)
SetCursorPos是直接设置鼠标绝对坐标,要实现缓慢移动,核心是把总位移拆成多个微小步长,每移动一小步就短暂停顿,模拟自然的慢速移动。
示例代码:
import win32api import time def slow_move_cursor(start_x, start_y, end_x, end_y, duration=2): # 计算总位移 delta_x = end_x - start_x delta_y = end_y - start_y # 按总时长拆分步数(每秒50步,可按需调整) steps = int(duration * 50) # 每步的位移增量 step_x = delta_x / steps step_y = delta_y / steps current_x, current_y = start_x, start_y for _ in range(steps): current_x += step_x current_y += step_y # 取整后设置坐标 win32api.SetCursorPos((int(current_x), int(current_y))) # 控制每步间隔,保证总时长符合设置 time.sleep(duration / steps) # 调用示例:从(100,100)用2秒移动到(500,500) slow_move_cursor(100, 100, 500, 500, 2)
方法二:改进mouse_event实现慢移
你之前用mouse_event直接传相对位移时,Windows会根据系统鼠标速度设置自动调整,导致速度控制不准。改用绝对位移模式(配合MOUSEEVENTF_ABSOLUTE),把屏幕坐标转成0-65535的系统标准范围,再拆分小步移动,就能精准控制速度。
示例代码:
import win32api import win32con import time def slow_move_mouse_event(start_x, start_y, end_x, end_y, duration=2): # 获取当前屏幕分辨率 screen_width = win32api.GetSystemMetrics(0) screen_height = win32api.GetSystemMetrics(1) # 把屏幕坐标转成系统绝对坐标范围(0-65535) start_abs_x = int(start_x * 65535 / screen_width) start_abs_y = int(start_y * 65535 / screen_height) end_abs_x = int(end_x * 65535 / screen_width) end_abs_y = int(end_y * 65535 / screen_height) delta_x = end_abs_x - start_abs_x delta_y = end_abs_y - start_abs_y steps = int(duration * 50) step_x = delta_x / steps step_y = delta_y / steps current_abs_x, current_abs_y = start_abs_x, start_abs_y for _ in range(steps): current_abs_x += step_x current_abs_y += step_y # 发送绝对移动事件 win32api.mouse_event( win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE, int(current_abs_x), int(current_abs_y), 0, 0 ) time.sleep(duration / steps) # 调用示例:从(100,100)用1.5秒移动到(300,400) slow_move_mouse_event(100, 100, 300, 400, 1.5)
关键说明
- 两种方法都是通过拆分位移+短延时实现慢移,
duration参数控制总移动时间,数值越大速度越慢。 - SetCursorPos逻辑更直观,直接操作屏幕坐标,适合大多数场景;mouse_event的绝对模式更贴近系统原生鼠标事件逻辑。
- 你之前的代码用了放大系数(*2、*5等),这会加快移动速度,要降速只需缩小步长,或者增加总时长参数。
内容的提问来源于stack exchange,提问作者NitoTech
相关产品推荐
相关产品推荐

