用户反馈: 点击有时候一直点也没点上, 位置明明正确。
---
## 实测排查过程
第一版假设是两个时序问题(按下 30ms 太短 / 移动后立刻按下)。实测否决:
press= 30ms -> 画面切换 4/4
press= 60ms -> 画面切换 4/4
press=120ms -> 画面切换 4/4
在干净环境里三种时长全中, 所以时长不是元凶。
(第一版测试本身有缺陷: 它只验证 click() 返回 True, 而 True 只代表"定位
到了", 不代表游戏收到点击。改成截图前后比对画面是否变化才有意义。)
真实原因: **前台不是游戏**。现场证据:
窗口位置: (-7, 0) ← 出界
前台窗口: '...DeepSeek Harness' ← 不是游戏
点击结果: True ← 但光标最后在 (204,1063), 没到目标
排查中还否定了一个想当然的结论: 窗口出界**本身不致命**(坐标按实际窗口位置
算, 目标只要还在屏幕内就能点中) —— 实测窗口在 (-8,0) 时画面照样切换成功。
真正致命的是前台窗口不是游戏。
## 修复
click() 加 require_foreground 校验。**关键是比对句柄而不是比对矩形**:
第一版只判断"点击点是否落在前台窗口矩形内", 结果把浏览器切到前台、点游戏里
同一个坐标, 校验**照样通过** —— 那个屏幕坐标同时也落在浏览器窗口的矩形里。
窗口重叠时几何判断毫无意义。
现在给了 hwnd 就要求前台窗口就是它(或是它的子窗口), 否则拒绝并说明"这次点击
会打到别的窗口"。DriverInput 新增 bind_window(), 代理安装时自动绑定游戏句柄。
拒绝比静默失败好: 以前"点了个寂寞"也返回 True, AALC 无从知道要重试。
## 顺带调整
press_ms 30 -> 60, 定位成功后加 settle 间隔。这两项实测在干净环境下不是必需,
但负载高/掉帧时更稳, 成本只有几十毫秒。
## 验证
真机(游戏窗口 133358):
[1] 前台是 DSH -> False | 前台不是目标窗口(前台='...DeepSeek Harness',
目标='LimbusCompany') —— 这次点击会打到别的窗口
[2] DSH 在前台同点 -> False | 同上(正确拒绝)
[3] 游戏在前台 -> True | ok
测试新增 HwndForegroundCheckTest 4 个 + ForegroundCheckTest 6 个, 全套 441 通过。
290 lines
11 KiB
Python
290 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""罗技驱动级输入(logitech.driver.dll)。
|
|
|
|
为什么需要它: 用 SendInput/mouse_event 注入的点击, 游戏侧仍可能识别为"模拟"。
|
|
这个 DLL 通过罗技驱动的虚拟 HID 设备发事件。
|
|
|
|
⛔ 两个必须知道的前提(2026-10-22 实测):
|
|
|
|
1. **会话必须是物理 console**
|
|
RDP 新建的是独立会话, 和物理桌面隔离。在 RDP 会话里调 `moveR` 光标纹丝不动
|
|
(实测 22 次采样全程 (1043,758) 不动), 切到 console 会话后立刻正常。
|
|
比较当前进程会话与 WTSGetActiveConsoleSessionId; 前台窗口句柄不能判定会话类型。
|
|
|
|
2. **必须关掉指针加速**
|
|
加速开着时 counts→像素是非线性的(实测 +100/+200/+400 对应 -45/-3/-3 像素),
|
|
当时的速度设置下关闭后比值为 1.0000。没关的话本模块会报警并拒绝定位,
|
|
而不是给出一个不准的位置。
|
|
|
|
接口只用 `device_open / moveR / mouse_down / mouse_up / key_down / key_up / scroll`,
|
|
这是 logitech.test.py 里验证过的那几个。
|
|
"""
|
|
import ctypes
|
|
import os
|
|
import time
|
|
from ctypes import wintypes
|
|
from functools import lru_cache
|
|
|
|
# win32 SPI 常量
|
|
SPI_GETMOUSE = 0x0003
|
|
SPI_GETMOUSESPEED = 0x0070
|
|
|
|
DEFAULT_DLL = r'E:\罗技键鼠驱动\logitech.driver.dll'
|
|
|
|
|
|
class Cursor(ctypes.Structure):
|
|
_fields_ = [('x', ctypes.c_long), ('y', ctypes.c_long)]
|
|
|
|
|
|
@lru_cache(maxsize=None)
|
|
def _win_library(name):
|
|
# 使用独立绑定, 避免 argtypes 污染 AALC/pyautogui 共用的 ctypes.windll。
|
|
return ctypes.WinDLL(name, use_last_error=True)
|
|
|
|
|
|
def _api(library, name, result, args):
|
|
fn = getattr(_win_library(library), name)
|
|
fn.restype, fn.argtypes = result, args
|
|
return fn
|
|
|
|
|
|
def get_cursor():
|
|
c = Cursor()
|
|
fn = _api('user32', 'GetCursorPos', wintypes.BOOL, [ctypes.POINTER(Cursor)])
|
|
if not fn(ctypes.byref(c)):
|
|
raise OSError('GetCursorPos 失败')
|
|
return (c.x, c.y)
|
|
|
|
|
|
def foreground_window():
|
|
return _api('user32', 'GetForegroundWindow', wintypes.HWND, [])()
|
|
|
|
|
|
def is_console_session():
|
|
current = wintypes.DWORD()
|
|
query = _api('kernel32', 'ProcessIdToSessionId', wintypes.BOOL,
|
|
[wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)])
|
|
if not query(os.getpid(), ctypes.byref(current)):
|
|
raise OSError('ProcessIdToSessionId 失败')
|
|
console = _api('kernel32', 'WTSGetActiveConsoleSessionId', wintypes.DWORD, [])()
|
|
return console != 0xFFFFFFFF and current.value == console
|
|
|
|
|
|
def has_foreground():
|
|
"""当前是否存在前台窗口; 激活切换时也可能短暂为 0。"""
|
|
return bool(foreground_window())
|
|
|
|
|
|
def acceleration_on():
|
|
"""指针加速是否开着。开着就别指望 counts 和像素成线性。"""
|
|
a = (ctypes.c_int * 3)()
|
|
fn = _api('user32', 'SystemParametersInfoA', wintypes.BOOL,
|
|
[wintypes.UINT, wintypes.UINT, ctypes.c_void_p, wintypes.UINT])
|
|
if not fn(SPI_GETMOUSE, 0, ctypes.byref(a), 0):
|
|
raise OSError('读取指针加速设置失败')
|
|
return bool(a[2])
|
|
|
|
|
|
def mouse_speed():
|
|
s = ctypes.c_int()
|
|
fn = _api('user32', 'SystemParametersInfoA', wintypes.BOOL,
|
|
[wintypes.UINT, wintypes.UINT, ctypes.c_void_p, wintypes.UINT])
|
|
if not fn(SPI_GETMOUSESPEED, 0, ctypes.byref(s), 0):
|
|
raise OSError('读取指针速度失败')
|
|
return s.value
|
|
|
|
|
|
class DriverInput:
|
|
"""罗技驱动级鼠标/键盘。
|
|
|
|
定位采用**闭环**: 发相对位移 -> 读回实际位置 -> 不够就再发, 直到误差 <= tol。
|
|
这样不依赖任何标定常数, 也能对抗偶发的坐标跳变。
|
|
"""
|
|
|
|
def __init__(self, dll_path=None, log=print):
|
|
self.dll_path = dll_path or os.environ.get('LCP_LOGITECH_DLL') or DEFAULT_DLL
|
|
self.log = log
|
|
self._dll = None
|
|
self._open = False
|
|
# 目标窗口句柄。有它才能做句柄级前台校验 —— 几何校验在窗口重叠时没用:
|
|
# 实测把浏览器切到前台, 点游戏里同一个坐标, 只比矩形的话校验照样通过。
|
|
self.hwnd = 0
|
|
|
|
def bind_window(self, hwnd):
|
|
"""绑定目标窗口。绑定后 click() 会做句柄级前台校验。"""
|
|
self.hwnd = int(hwnd or 0)
|
|
return self
|
|
|
|
# ---------------------------------------------------------------- 生命周期
|
|
|
|
def open(self):
|
|
if self._open:
|
|
return True
|
|
if not os.path.exists(self.dll_path):
|
|
self.log('[driver] 找不到 %s' % self.dll_path)
|
|
return False
|
|
try:
|
|
self._dll = ctypes.CDLL(self.dll_path)
|
|
for name in ('device_open', 'moveR', 'mouse_down', 'mouse_up'):
|
|
getattr(self._dll, name)
|
|
ok = self._dll.device_open() == 1
|
|
except (OSError, AttributeError) as e:
|
|
self.log('[driver] 加载 DLL 失败: %s' % e)
|
|
self._dll = None
|
|
return False
|
|
self._open = bool(ok)
|
|
if not ok:
|
|
self.log('[driver] device_open() != 1, 罗技驱动未就绪')
|
|
return self._open
|
|
|
|
@property
|
|
def ready(self):
|
|
return self._open and self._dll is not None
|
|
|
|
def preflight(self):
|
|
"""返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。"""
|
|
if not self.open():
|
|
return False, '罗技驱动不可用(device_open 失败)'
|
|
try:
|
|
if not is_console_session():
|
|
return False, '当前进程不在物理 console 会话, 不启用驱动输入'
|
|
if not has_foreground():
|
|
return False, '当前会话没有前台窗口(GetForegroundWindow=0), 暂不启用驱动输入'
|
|
if acceleration_on():
|
|
return False, ('指针加速开着, counts 与像素不成比例, 定位会不准 —— '
|
|
'关掉"提高指针精确度"后重试')
|
|
except (OSError, AttributeError) as e:
|
|
return False, '无法确认输入环境: %s' % e
|
|
return True, 'ok'
|
|
|
|
# ---------------------------------------------------------------- 移动
|
|
|
|
def move_relative(self, dx, dy):
|
|
if not self.ready:
|
|
return False
|
|
if dx == 0 and dy == 0:
|
|
return True
|
|
self._dll.moveR(int(dx), int(dy), True)
|
|
return True
|
|
|
|
def move_to(self, sx, sy, tol=1, iters=10, settle=0.03):
|
|
"""把光标精确移到屏幕坐标 (sx, sy)。返回是否到位。"""
|
|
if not self.ready:
|
|
return False
|
|
for _ in range(iters):
|
|
cx, cy = get_cursor()
|
|
dx, dy = int(sx) - cx, int(sy) - cy
|
|
if abs(dx) <= tol and abs(dy) <= tol:
|
|
return True
|
|
if self.move_relative(dx, dy) is False:
|
|
return False
|
|
time.sleep(settle)
|
|
cx, cy = get_cursor()
|
|
return abs(int(sx) - cx) <= tol and abs(int(sy) - cy) <= tol
|
|
|
|
# ---------------------------------------------------------------- 按键
|
|
|
|
def down(self, button=1):
|
|
if self.ready:
|
|
self._dll.mouse_down(int(button))
|
|
|
|
def up(self, button=1):
|
|
if self.ready:
|
|
self._dll.mouse_up(int(button))
|
|
|
|
def click(self, sx, sy, times=1, tol=1, require_foreground=True,
|
|
press_ms=60, settle=0.05):
|
|
"""先确认到位置, 再按下抬起。
|
|
|
|
⛔ 三个已验证的"位置对却点不上"原因(2026-10-23 实测):
|
|
1. **前台不是游戏** —— 点击会送给当前前台窗口。实测: 窗口位置正确、坐标
|
|
换算正确, 但前台是别的窗口, 结果点了个寂寞, 而旧版这里照样返回 True。
|
|
现在用 require_foreground 检查: 点击点必须落在**前台窗口的客户区**内,
|
|
否则拒绝并报错 —— 宁可失败也不要静默点错地方。
|
|
2. **移动后立刻按下** —— 游戏按帧采样, 移动还没被处理就点击, 会算在旧位置。
|
|
所以定位成功后先 settle 再按。
|
|
3. **按下时间太短** —— 默认 30ms 在掉帧时会漏; 改成 60ms。
|
|
实测 30/60/120ms 在干净环境下都能中, 但 60ms 对负载高的情况更稳。
|
|
"""
|
|
if not self.ready:
|
|
return False
|
|
if not self.move_to(sx, sy, tol=tol):
|
|
cx, cy = get_cursor()
|
|
self.log('[driver] 定位失败: 目标(%d,%d) 实际(%d,%d), 不点击'
|
|
% (sx, sy, cx, cy))
|
|
return False
|
|
if require_foreground:
|
|
ok, why = click_point_is_on_foreground(sx, sy, self.hwnd or None)
|
|
if not ok:
|
|
self.log('[driver] 拒绝点击(%d,%d): %s' % (sx, sy, why))
|
|
return False
|
|
if settle:
|
|
time.sleep(settle)
|
|
for _ in range(int(times)):
|
|
try:
|
|
self._dll.mouse_down(1)
|
|
time.sleep(press_ms / 1000.0)
|
|
finally:
|
|
self._dll.mouse_up(1)
|
|
return True
|
|
|
|
def key_down(self, key):
|
|
if self.ready:
|
|
self._dll.key_down(key)
|
|
|
|
def key_up(self, key):
|
|
if self.ready:
|
|
self._dll.key_up(key)
|
|
|
|
def scroll(self, amount):
|
|
if self.ready:
|
|
self._dll.scroll(int(amount))
|
|
|
|
|
|
def click_point_is_on_foreground(sx, sy, hwnd=None):
|
|
"""(屏幕坐标) 是否安全可点。
|
|
|
|
返回 (是否安全, 原因)。
|
|
|
|
⛔ 为什么必须比对句柄而不是比对矩形(2026-10-23 实测教训):
|
|
最初只判断"点击点落在前台窗口的矩形内", 结果把浏览器切到前台、点游戏里
|
|
同一个坐标, 校验**照样通过** —— 因为那个屏幕坐标同时也落在浏览器窗口的
|
|
矩形里。几何判断在窗口互相重叠时毫无意义。
|
|
|
|
所以: 给了 hwnd 就要求前台窗口**就是它**(或是它的子窗口); 没给 hwnd 时
|
|
退化成"有前台窗口且点在它矩形内", 可用性有限, 仅作兜底。
|
|
"""
|
|
user32 = ctypes.windll.user32
|
|
fg = user32.GetForegroundWindow()
|
|
if not fg:
|
|
return False, '当前没有前台窗口(GetForegroundWindow=0)'
|
|
if hwnd:
|
|
if fg == hwnd or user32.IsChild(hwnd, fg):
|
|
return True, 'ok'
|
|
buf = ctypes.create_unicode_buffer(64)
|
|
user32.GetWindowTextW(fg, buf, 64)
|
|
other = ctypes.create_unicode_buffer(64)
|
|
user32.GetWindowTextW(hwnd, other, 64)
|
|
return False, ('前台不是目标窗口(前台=%r, 目标=%r) —— 这次点击会打到别的窗口'
|
|
% (buf.value, other.value))
|
|
pt = wintypes.POINT(int(sx), int(sy))
|
|
rect = wintypes.RECT()
|
|
if not user32.GetWindowRect(fg, ctypes.byref(rect)):
|
|
return False, '取不到前台窗口的区域'
|
|
if not (rect.left <= pt.x < rect.right and rect.top <= pt.y < rect.bottom):
|
|
return False, ('点击点(%d,%d)不在前台窗口内(区域 %d,%d-%d,%d)'
|
|
% (pt.x, pt.y, rect.left, rect.top, rect.right, rect.bottom))
|
|
return True, 'ok'
|
|
|
|
|
|
def client_to_screen(hwnd, x, y):
|
|
"""游戏客户区坐标 -> 屏幕坐标。"""
|
|
if not hwnd:
|
|
raise OSError('没有游戏窗口句柄')
|
|
pt = wintypes.POINT(int(x), int(y))
|
|
fn = _api('user32', 'ClientToScreen', wintypes.BOOL,
|
|
[wintypes.HWND, ctypes.POINTER(wintypes.POINT)])
|
|
if not fn(hwnd, ctypes.byref(pt)):
|
|
raise OSError('ClientToScreen 失败, 未发送输入')
|
|
return (pt.x, pt.y)
|