如何让游戏识别脚本模拟的鼠标操作而非仅响应真实鼠标?
解决游戏中软件模拟鼠标无响应的问题
很多Steam游戏(尤其是带反作弊或使用原生输入的游戏)会过滤掉操作系统API层面的模拟输入,只识别硬件级的鼠标信号,这就是你用pyautogui、pynput这类库没效果的核心原因。给你几个可行的解决方向:
- 改用硬件级输入模拟:直接调用Windows底层API发送鼠标事件,这种方式更接近真实鼠标的硬件信号,不容易被游戏拦截。用
ctypes实现的示例代码如下:
import ctypes import time # 定义Windows API常量 INPUT_MOUSE = 0 MOUSEEVENTF_MOVE = 0x0001 MOUSEEVENTF_LEFTDOWN = 0x0002 MOUSEEVENTF_LEFTUP = 0x0004 class INPUT(ctypes.Structure): _fields_ = [("type", ctypes.c_ulong), ("mi", ctypes.c_byte * 40)] class MOUSEINPUT(ctypes.Structure): _fields_ = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong))] def send_mouse_input(x, y, flags): # 转换为Windows API要求的虚拟坐标(范围-32768到32767) screen_width = ctypes.windll.user32.GetSystemMetrics(0) screen_height = ctypes.windll.user32.GetSystemMetrics(1) dx = int((x / screen_width) * 65535) dy = int((y / screen_height) * 65535) mi = MOUSEINPUT(dx, dy, 0, flags, 0, None) input_obj = INPUT(INPUT_MOUSE, ctypes.cast(ctypes.pointer(mi), ctypes.POINTER(ctypes.c_byte * 40)).contents) ctypes.windll.user32.SendInput(1, ctypes.pointer(input_obj), ctypes.sizeof(input_obj)) def openWorld(): # 模拟平滑移动鼠标到目标位置(分多次发送移动事件) current_x = ctypes.c_int() current_y = ctypes.c_int() ctypes.windll.user32.GetCursorPos(ctypes.byref(current_x), ctypes.byref(current_y)) target_x, target_y = 230, 530 steps = 20 for i in range(steps): step_x = int((target_x - current_x.value) * (i+1)/steps) step_y = int((target_y - current_y.value) * (i+1)/steps) send_mouse_input(current_x.value + step_x, current_y.value + step_y, MOUSEEVENTF_MOVE) time.sleep(0.01) # 发送完整的左键点击事件(按下+抬起) send_mouse_input(target_x, target_y, MOUSEEVENTF_LEFTDOWN) time.sleep(0.05) send_mouse_input(target_x, target_y, MOUSEEVENTF_LEFTUP)
以管理员权限运行脚本:如果游戏是用管理员权限启动的,脚本也需要同样权限,否则系统可能拦截输入信号。
调整游戏输入设置:关闭游戏里的「原始输入」选项(如果存在),部分游戏开启该选项后会绕过系统输入层,直接读取硬件信号,导致软件模拟失效。
尝试AutoHotkey的硬件模拟:如果Python的方法仍无效,AutoHotkey的
SendInput或SendPlay模式专门针对游戏输入做了优化,你可以写个简单的AHK脚本,再用Python调用它。
内容的提问来源于stack exchange,提问作者SuperCodingWizard
相关产品推荐
相关产品推荐

