复核驱动输入与窗口补丁,修复接管互斥和异常清理
This commit is contained in:
+42
-58
@@ -8,6 +8,7 @@ import glob
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
from .engine import Engine
|
from .engine import Engine
|
||||||
|
|
||||||
@@ -228,42 +229,41 @@ class AalcEngine(Engine):
|
|||||||
win32con.SWP_NOSIZE | win32con.SWP_NOZORDER |
|
win32con.SWP_NOSIZE | win32con.SWP_NOZORDER |
|
||||||
win32con.SWP_NOACTIVATE)
|
win32con.SWP_NOACTIVATE)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _background_target(self, x, y):
|
||||||
|
position = None
|
||||||
|
transparent = self.cfg.win_input_type == 'window_move'
|
||||||
|
try:
|
||||||
|
if transparent:
|
||||||
|
self.screen.handle.set_window_transparent(True)
|
||||||
|
position = self.auto.input_handler._set_window_pos(int(x), int(y))
|
||||||
|
self.auto.input_handler.set_active()
|
||||||
|
yield position
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
if position is not None:
|
||||||
|
try:
|
||||||
|
time.sleep(0.12)
|
||||||
|
finally:
|
||||||
|
self._restore_background_position(position)
|
||||||
|
finally:
|
||||||
|
if transparent:
|
||||||
|
self.screen.handle.set_window_transparent(False)
|
||||||
|
|
||||||
def click(self, x, y, times=1):
|
def click(self, x, y, times=1):
|
||||||
self._prepare_input()
|
self._prepare_input()
|
||||||
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
|
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
|
||||||
import win32con
|
import win32con
|
||||||
handler = self.auto.input_handler
|
|
||||||
self.auto.wait_pause()
|
self.auto.wait_pause()
|
||||||
for _ in range(int(times)):
|
for _ in range(int(times)):
|
||||||
position = None
|
with self._background_target(x, y):
|
||||||
transparent = False
|
self._background_mouse(win32con.WM_MOUSEMOVE, x, y)
|
||||||
if self.cfg.win_input_type == 'window_move':
|
|
||||||
# 搬到光标下面时设成透明/点击穿透, 免得挡住用户的光标。
|
|
||||||
# ⛔ 必须在本次点击结束时就还原: 以前只有 background_screenshot
|
|
||||||
# 会把它恢复成 False, 于是"点击 -> 截图 -> 点击 -> 截图"这种
|
|
||||||
# 高频交替会让游戏窗口在不可见/可见之间反复切换 —— 肉眼看就是
|
|
||||||
# 画面一直抽搐。AALC 自己的 WindowMoveInput.mouse_click 根本不碰
|
|
||||||
# 透明度, 所以它只是"跳一下", 不会闪。
|
|
||||||
self.screen.handle.set_window_transparent(True)
|
|
||||||
transparent = True
|
|
||||||
position = handler._set_window_pos(int(x), int(y))
|
|
||||||
handler.set_active()
|
|
||||||
self._background_mouse(win32con.WM_MOUSEMOVE, x, y)
|
|
||||||
time.sleep(0.12)
|
|
||||||
self._background_mouse(win32con.WM_LBUTTONDOWN, x, y, held=True)
|
|
||||||
try:
|
|
||||||
time.sleep(0.12)
|
time.sleep(0.12)
|
||||||
finally:
|
|
||||||
# 嵌套 try/finally: 还原位置那步也可能抛错(比如任务被停),
|
|
||||||
# 但透明度**无论如何**都要还原, 否则窗口会一直隐形。
|
|
||||||
try:
|
try:
|
||||||
self._background_mouse(win32con.WM_LBUTTONUP, x, y)
|
self._background_mouse(win32con.WM_LBUTTONDOWN, x, y, held=True)
|
||||||
if position is not None:
|
time.sleep(0.12)
|
||||||
time.sleep(0.12)
|
|
||||||
self._restore_background_position(position)
|
|
||||||
finally:
|
finally:
|
||||||
if transparent:
|
self._background_mouse(win32con.WM_LBUTTONUP, x, y)
|
||||||
self.screen.handle.set_window_transparent(False)
|
|
||||||
# Let Unity consume the release before another target is selected.
|
# Let Unity consume the release before another target is selected.
|
||||||
time.sleep(0.12)
|
time.sleep(0.12)
|
||||||
elif not self.cfg.simulator and self.cfg.win_input_type == 'foreground':
|
elif not self.cfg.simulator and self.cfg.win_input_type == 'foreground':
|
||||||
@@ -318,40 +318,24 @@ class AalcEngine(Engine):
|
|||||||
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
|
if not self.cfg.simulator and self.cfg.win_input_type in ('background', 'window_move'):
|
||||||
import win32con
|
import win32con
|
||||||
self.auto.wait_pause()
|
self.auto.wait_pause()
|
||||||
position = None
|
with self._background_target(from_x, from_y) as position:
|
||||||
transparent = False
|
self._background_mouse(win32con.WM_MOUSEMOVE, from_x, from_y)
|
||||||
if self.cfg.win_input_type == 'window_move':
|
|
||||||
# 同 click(): 透明必须在本次拖动结束时就还原, 不能留给下一次截图
|
|
||||||
self.screen.handle.set_window_transparent(True)
|
|
||||||
transparent = True
|
|
||||||
position = self.auto.input_handler._set_window_pos(int(from_x), int(from_y))
|
|
||||||
self.auto.input_handler.set_active()
|
|
||||||
self._background_mouse(win32con.WM_MOUSEMOVE, from_x, from_y)
|
|
||||||
time.sleep(0.12)
|
|
||||||
self._background_mouse(win32con.WM_LBUTTONDOWN, from_x, from_y, held=True)
|
|
||||||
last_x, last_y = from_x, from_y
|
|
||||||
try:
|
|
||||||
time.sleep(0.12)
|
time.sleep(0.12)
|
||||||
steps = max(1, int(float(duration) / 0.02))
|
last_x, last_y = from_x, from_y
|
||||||
for step in range(1, steps + 1):
|
|
||||||
last_x = round(from_x + (to_x - from_x) * step / steps)
|
|
||||||
last_y = round(from_y + (to_y - from_y) * step / steps)
|
|
||||||
if position is not None:
|
|
||||||
self.auto.input_handler._set_window_pos(last_x, last_y)
|
|
||||||
self._background_mouse(win32con.WM_MOUSEMOVE, last_x, last_y, held=True)
|
|
||||||
time.sleep(float(duration) / steps)
|
|
||||||
time.sleep(0.12)
|
|
||||||
finally:
|
|
||||||
# 同 click(): 透明度必须在嵌套的 finally 里还原, 不能被还原位置那步的
|
|
||||||
# 异常跳过, 否则窗口会一直隐形。
|
|
||||||
try:
|
try:
|
||||||
self._background_mouse(win32con.WM_LBUTTONUP, last_x, last_y)
|
self._background_mouse(win32con.WM_LBUTTONDOWN, from_x, from_y, held=True)
|
||||||
if position is not None:
|
time.sleep(0.12)
|
||||||
time.sleep(0.12)
|
steps = max(1, int(float(duration) / 0.02))
|
||||||
self._restore_background_position(position)
|
for step in range(1, steps + 1):
|
||||||
|
last_x = round(from_x + (to_x - from_x) * step / steps)
|
||||||
|
last_y = round(from_y + (to_y - from_y) * step / steps)
|
||||||
|
if position is not None:
|
||||||
|
self.auto.input_handler._set_window_pos(last_x, last_y)
|
||||||
|
self._background_mouse(win32con.WM_MOUSEMOVE, last_x, last_y, held=True)
|
||||||
|
time.sleep(float(duration) / steps)
|
||||||
|
time.sleep(0.12)
|
||||||
finally:
|
finally:
|
||||||
if transparent:
|
self._background_mouse(win32con.WM_LBUTTONUP, last_x, last_y)
|
||||||
self.screen.handle.set_window_transparent(False)
|
|
||||||
return
|
return
|
||||||
if not self.cfg.simulator and self.cfg.win_input_type == 'foreground':
|
if not self.cfg.simulator and self.cfg.win_input_type == 'foreground':
|
||||||
import pyautogui
|
import pyautogui
|
||||||
|
|||||||
+75
-31
@@ -16,6 +16,7 @@ import os
|
|||||||
import re
|
import re
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
|
TEAM_TARGET = re.compile(r'(?:TEAMS|TFAMS|编队)#(\d+)', re.IGNORECASE)
|
||||||
|
|
||||||
@@ -98,10 +99,8 @@ class WindowGuard(threading.Thread):
|
|||||||
|
|
||||||
# ---------------------------------------------------------------- 驱动级点击接管
|
# ---------------------------------------------------------------- 驱动级点击接管
|
||||||
|
|
||||||
# AALC 的 automation.py 在初始化时把这些名字绑成了别名
|
# 新版 AALC 的输入入口带交互门和锁, 重绑时必须保留这些包装。
|
||||||
# (self.mouse_click = self.input_handler.mouse_click 之类), 所以换掉 input_handler
|
REBIND_NAMES = ('mouse_click', 'mouse_click_blank', 'mouse_down', 'mouse_up')
|
||||||
# 还不够, 必须把别名一起重绑, 否则任务流里调的还是老方法。
|
|
||||||
REBIND_NAMES = ('mouse_click', 'mouse_down', 'mouse_up')
|
|
||||||
|
|
||||||
|
|
||||||
class DriverClickProxy:
|
class DriverClickProxy:
|
||||||
@@ -125,8 +124,15 @@ class DriverClickProxy:
|
|||||||
|
|
||||||
# --- 接管 -------------------------------------------------------------
|
# --- 接管 -------------------------------------------------------------
|
||||||
def _screen_pos(self, x, y):
|
def _screen_pos(self, x, y):
|
||||||
from .driver_input import client_to_screen
|
from .driver_input import client_to_screen, foreground_window, is_console_session
|
||||||
hwnd = self._screen.handle.hwnd
|
handle = self._screen.handle
|
||||||
|
hwnd = handle.hwnd
|
||||||
|
if not hwnd or handle.isMinimized or not is_console_session():
|
||||||
|
raise OSError('驱动点击需要 console 会话中可见的游戏窗口')
|
||||||
|
if foreground_window() != hwnd:
|
||||||
|
handle.setForeground()
|
||||||
|
if foreground_window() != hwnd:
|
||||||
|
raise OSError('无法激活游戏窗口, 未发送驱动输入')
|
||||||
return client_to_screen(hwnd, x, y)
|
return client_to_screen(hwnd, x, y)
|
||||||
|
|
||||||
def _trace(self, msg):
|
def _trace(self, msg):
|
||||||
@@ -140,35 +146,48 @@ class DriverClickProxy:
|
|||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def mouse_click(self, x, y, times=1, *args, **kwargs):
|
def mouse_click(self, x, y, times=1, move_back=False):
|
||||||
|
from .driver_input import get_cursor
|
||||||
|
self._handler.wait_pause()
|
||||||
self._trace('mouse_click(%s,%s,times=%s)' % (x, y, times))
|
self._trace('mouse_click(%s,%s,times=%s)' % (x, y, times))
|
||||||
|
original_pos = None
|
||||||
try:
|
try:
|
||||||
sx, sy = self._screen_pos(x, y)
|
sx, sy = self._screen_pos(x, y)
|
||||||
except Exception as e:
|
if move_back:
|
||||||
self._trace('screen_pos 失败: %s: %s' % (type(e).__name__, e))
|
original_pos = get_cursor()
|
||||||
|
if self._driver.click(sx, sy, times=times):
|
||||||
|
self.clicks += 1
|
||||||
|
self.log('[driver] 点击客户区(%d,%d) -> 屏幕(%d,%d)' % (x, y, sx, sy))
|
||||||
|
return True
|
||||||
|
except InterruptedError:
|
||||||
raise
|
raise
|
||||||
if self._driver.click(sx, sy, times=times):
|
except OSError as e:
|
||||||
self.clicks += 1
|
self._trace('点击失败: %s' % e)
|
||||||
self.log('[driver] 点击客户区(%d,%d) -> 屏幕(%d,%d)' % (x, y, sx, sy))
|
self.log('[driver] 点击失败: %s' % e)
|
||||||
self._handler.wait_pause()
|
finally:
|
||||||
return True
|
if original_pos is not None:
|
||||||
|
self._driver.move_to(*original_pos)
|
||||||
self.refused += 1
|
self.refused += 1
|
||||||
self.log('[driver] 放弃点击客户区(%d,%d): 无法精确定位' % (x, y))
|
self.log('[driver] 放弃点击客户区(%d,%d): 无法激活或精确定位' % (x, y))
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def mouse_down(self, x=None, y=None, *args, **kwargs):
|
def mouse_click_blank(self, coordinate=(1, 1), times=1, move_back=False):
|
||||||
if x is not None and y is not None:
|
return self.mouse_click(*coordinate, times=times, move_back=move_back)
|
||||||
sx, sy = self._screen_pos(x, y)
|
|
||||||
if not self._driver.move_to(sx, sy):
|
def mouse_down(self, x, y):
|
||||||
return False
|
self._handler.wait_pause()
|
||||||
|
sx, sy = self._screen_pos(x, y)
|
||||||
|
if not self._driver.move_to(sx, sy):
|
||||||
|
return False
|
||||||
self._driver.down(1)
|
self._driver.down(1)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def mouse_up(self, x=None, y=None, *args, **kwargs):
|
def mouse_up(self, x, y):
|
||||||
if x is not None and y is not None:
|
try:
|
||||||
sx, sy = self._screen_pos(x, y)
|
sx, sy = self._screen_pos(x, y)
|
||||||
self._driver.move_to(sx, sy)
|
self._driver.move_to(sx, sy)
|
||||||
self._driver.up(1)
|
finally:
|
||||||
|
self._driver.up(1)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@@ -180,7 +199,9 @@ def install_driver_click(auto, screen, driver=None, log=print):
|
|||||||
"""
|
"""
|
||||||
from .driver_input import DriverInput
|
from .driver_input import DriverInput
|
||||||
|
|
||||||
drv = driver or DriverInput(log=log)
|
if isinstance(auto.input_handler, DriverClickProxy):
|
||||||
|
return auto.input_handler._driver
|
||||||
|
drv = driver if driver is not None else DriverInput(log=log)
|
||||||
ok, why = drv.preflight()
|
ok, why = drv.preflight()
|
||||||
if not ok:
|
if not ok:
|
||||||
log('[lc_mcp] 驱动级输入未启用: %s' % why)
|
log('[lc_mcp] 驱动级输入未启用: %s' % why)
|
||||||
@@ -199,10 +220,31 @@ def install_driver_click(auto, screen, driver=None, log=print):
|
|||||||
pass
|
pass
|
||||||
auto.input_handler = proxy
|
auto.input_handler = proxy
|
||||||
for name in REBIND_NAMES:
|
for name in REBIND_NAMES:
|
||||||
if hasattr(proxy, name):
|
gate = getattr(auto, '_run_business_interaction', None)
|
||||||
setattr(auto, name, getattr(proxy, name))
|
setattr(auto, name, gate(name) if callable(gate) else getattr(proxy, name))
|
||||||
log('[lc_mcp] patch: 鼠标点击已切到罗技驱动级输入')
|
log('[lc_mcp] patch: 鼠标点击已切到罗技驱动级输入')
|
||||||
return drv
|
return drv
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def driver_click_tasks(scheme, auto, screen, cfg, log=print):
|
||||||
|
"""每次游戏初始化完成后接管, 包括 all 任务和故障重启。"""
|
||||||
|
if cfg.simulator or os.environ.get('LCP_DRIVER_INPUT', '').strip() != '1':
|
||||||
|
yield
|
||||||
|
return
|
||||||
|
original = scheme.init_game
|
||||||
|
|
||||||
|
def init_game(*args, **kwargs):
|
||||||
|
result = original(*args, **kwargs)
|
||||||
|
install_driver_click(auto, screen, log=log)
|
||||||
|
return result
|
||||||
|
|
||||||
|
scheme.init_game = init_game
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
scheme.init_game = original
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 前台窗口健壮化
|
# ---------------------------------------------------------------- 前台窗口健壮化
|
||||||
|
|
||||||
def install_robust_set_foreground(screen, log=print):
|
def install_robust_set_foreground(screen, log=print):
|
||||||
@@ -214,8 +256,8 @@ def install_robust_set_foreground(screen, log=print):
|
|||||||
失败时抛 pywintypes.error(0, 'SetForegroundWindow', ...) —— 这个异常在
|
失败时抛 pywintypes.error(0, 'SetForegroundWindow', ...) —— 这个异常在
|
||||||
set_win() 里没有捕获, 直接把任务带崩(观测: exit code 3 之前的 traceback)。
|
set_win() 里没有捕获, 直接把任务带崩(观测: exit code 3 之前的 traceback)。
|
||||||
|
|
||||||
兜底手法是 MSDN 认可的标准做法: 把自己的线程输入队列挂到当前前台窗口的
|
兜底尝试关联当前线程和前台线程的输入队列, 完成后解挂。
|
||||||
线程上, 借它的前台权限完成切换, 完成后解挂。
|
Windows 仍可能拒绝激活; 驱动输入在发送前另行检查游戏是否在前台。
|
||||||
"""
|
"""
|
||||||
handle = getattr(screen, 'handle', None)
|
handle = getattr(screen, 'handle', None)
|
||||||
if handle is None or not hasattr(handle, 'setForeground'):
|
if handle is None or not hasattr(handle, 'setForeground'):
|
||||||
@@ -243,16 +285,18 @@ def install_robust_set_foreground(screen, log=print):
|
|||||||
thread_me = win32api.GetCurrentThreadId()
|
thread_me = win32api.GetCurrentThreadId()
|
||||||
attached = False
|
attached = False
|
||||||
if thread_fg and thread_fg != thread_me:
|
if thread_fg and thread_fg != thread_me:
|
||||||
attached = bool(win32process.AttachThreadInput(thread_fg, thread_me, True))
|
# pywin32 成功时返回 None, 失败抛异常, 不能按真假判断。
|
||||||
|
win32process.AttachThreadInput(thread_me, thread_fg, True)
|
||||||
|
attached = True
|
||||||
try:
|
try:
|
||||||
win32gui.BringWindowToTop(hwnd)
|
win32gui.BringWindowToTop(hwnd)
|
||||||
win32gui.SetForegroundWindow(hwnd)
|
win32gui.SetForegroundWindow(hwnd)
|
||||||
finally:
|
finally:
|
||||||
if attached:
|
if attached:
|
||||||
win32process.AttachThreadInput(thread_fg, thread_me, False)
|
win32process.AttachThreadInput(thread_me, thread_fg, False)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log('[lc_mcp] setForeground 兜底也失败: %s: %s' % (type(e).__name__, e))
|
log('[lc_mcp] setForeground 兜底也失败: %s: %s' % (type(e).__name__, e))
|
||||||
|
|
||||||
handle.setForeground = setForeground
|
handle.setForeground = setForeground
|
||||||
log('[lc_mcp] patch: SetForegroundWindow 加 AttachThreadInput 兜底')
|
log('[lc_mcp] patch: SetForegroundWindow 加 AttachThreadInput 兜底')
|
||||||
return handle
|
return handle
|
||||||
|
|||||||
+26
-29
@@ -11,8 +11,8 @@ import sys
|
|||||||
|
|
||||||
from . import preflight
|
from . import preflight
|
||||||
from .aalc_engine import bootstrap
|
from .aalc_engine import bootstrap
|
||||||
from .aalc_patches import (WindowGuard, install_driver_click, install_exact_team_match,
|
from .aalc_patches import (WindowGuard, driver_click_tasks, install_exact_team_match,
|
||||||
install_robust_set_foreground)
|
install_robust_set_foreground)
|
||||||
|
|
||||||
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
|
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
|
||||||
TASKS = {
|
TASKS = {
|
||||||
@@ -88,34 +88,31 @@ def run(task, params):
|
|||||||
guard.start()
|
guard.start()
|
||||||
restore_path = os.environ.get(RESTORE_ENV)
|
restore_path = os.environ.get(RESTORE_ENV)
|
||||||
originals = apply_overrides(cfg, task, params, restore_path)
|
originals = apply_overrides(cfg, task, params, restore_path)
|
||||||
try:
|
with driver_click_tasks(scheme, auto, screen, cfg, log=log):
|
||||||
if task == 'all':
|
try:
|
||||||
scheme.script_task()
|
if task == 'all':
|
||||||
|
scheme.script_task()
|
||||||
|
return 0
|
||||||
|
# 与 script_task() 相同的前置步骤
|
||||||
|
scheme.init_game()
|
||||||
|
path_manager.initialize_paths()
|
||||||
|
auto.clear_img_cache()
|
||||||
|
retry_monitor.start()
|
||||||
|
get_reward = None
|
||||||
|
if auto.click_element('battle/turn_assets.png', take_screenshot=True):
|
||||||
|
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
|
||||||
|
get_reward = battle.fight()
|
||||||
|
{
|
||||||
|
'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
|
||||||
|
'reward': scheme.to_get_reward,
|
||||||
|
'enkephalin': scheme.Buy_enkephalin,
|
||||||
|
'mirror': scheme.Mirror_task,
|
||||||
|
}[task]()
|
||||||
return 0
|
return 0
|
||||||
# 与 script_task() 相同的前置步骤
|
finally:
|
||||||
scheme.init_game()
|
guard.stop()
|
||||||
# ⚠ 必须放在 init_game() 之后: 它会把 auto.input_handler 重建一次,
|
retry_monitor.stop()
|
||||||
# 放在前面装好的代理会被覆盖掉(2026-10-22 实测: 日志有 patch 记录但代理从未被调用)。
|
restore(cfg, originals, restore_path)
|
||||||
if os.environ.get('LCP_DRIVER_INPUT', '').strip() == '1':
|
|
||||||
install_driver_click(auto, screen, log=log)
|
|
||||||
path_manager.initialize_paths()
|
|
||||||
auto.clear_img_cache()
|
|
||||||
retry_monitor.start()
|
|
||||||
get_reward = None
|
|
||||||
if auto.click_element('battle/turn_assets.png', take_screenshot=True):
|
|
||||||
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
|
|
||||||
get_reward = battle.fight()
|
|
||||||
{
|
|
||||||
'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
|
|
||||||
'reward': scheme.to_get_reward,
|
|
||||||
'enkephalin': scheme.Buy_enkephalin,
|
|
||||||
'mirror': scheme.Mirror_task,
|
|
||||||
}[task]()
|
|
||||||
return 0
|
|
||||||
finally:
|
|
||||||
guard.stop()
|
|
||||||
retry_monitor.stop()
|
|
||||||
restore(cfg, originals, restore_path)
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv):
|
def main(argv):
|
||||||
|
|||||||
+64
-24
@@ -2,18 +2,18 @@
|
|||||||
"""罗技驱动级输入(logitech.driver.dll)。
|
"""罗技驱动级输入(logitech.driver.dll)。
|
||||||
|
|
||||||
为什么需要它: 用 SendInput/mouse_event 注入的点击, 游戏侧仍可能识别为"模拟"。
|
为什么需要它: 用 SendInput/mouse_event 注入的点击, 游戏侧仍可能识别为"模拟"。
|
||||||
这个 DLL 通过罗技驱动的虚拟 HID 设备发事件, 系统层面等同真鼠标。
|
这个 DLL 通过罗技驱动的虚拟 HID 设备发事件。
|
||||||
|
|
||||||
⛔ 两个必须知道的前提(2026-10-22 实测):
|
⛔ 两个必须知道的前提(2026-10-22 实测):
|
||||||
|
|
||||||
1. **会话必须是物理 console**
|
1. **会话必须是物理 console**
|
||||||
RDP 新建的是独立会话, 和物理桌面隔离。在 RDP 会话里调 `moveR` 光标纹丝不动
|
RDP 新建的是独立会话, 和物理桌面隔离。在 RDP 会话里调 `moveR` 光标纹丝不动
|
||||||
(实测 22 次采样全程 (1043,758) 不动), 切到 console 会话后立刻正常。
|
(实测 22 次采样全程 (1043,758) 不动), 切到 console 会话后立刻正常。
|
||||||
判断方法: `GetForegroundWindow()` 返回 0 就说明当前会话没有可接收输入的前台窗口。
|
比较当前进程会话与 WTSGetActiveConsoleSessionId; 前台窗口句柄不能判定会话类型。
|
||||||
|
|
||||||
2. **必须关掉指针加速**
|
2. **必须关掉指针加速**
|
||||||
加速开着时 counts→像素是非线性的(实测 +100/+200/+400 对应 -45/-3/-3 像素),
|
加速开着时 counts→像素是非线性的(实测 +100/+200/+400 对应 -45/-3/-3 像素),
|
||||||
关掉后严格 1 count = 1 像素(实测比值 1.0000)。没关的话本模块会报警并拒绝定位,
|
当时的速度设置下关闭后比值为 1.0000。没关的话本模块会报警并拒绝定位,
|
||||||
而不是给出一个不准的位置。
|
而不是给出一个不准的位置。
|
||||||
|
|
||||||
接口只用 `device_open / moveR / mouse_down / mouse_up / key_down / key_up / scroll`,
|
接口只用 `device_open / moveR / mouse_down / mouse_up / key_down / key_up / scroll`,
|
||||||
@@ -22,6 +22,8 @@
|
|||||||
import ctypes
|
import ctypes
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
from ctypes import wintypes
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
# win32 SPI 常量
|
# win32 SPI 常量
|
||||||
SPI_GETMOUSE = 0x0003
|
SPI_GETMOUSE = 0x0003
|
||||||
@@ -34,34 +36,61 @@ class Cursor(ctypes.Structure):
|
|||||||
_fields_ = [('x', ctypes.c_long), ('y', ctypes.c_long)]
|
_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():
|
def get_cursor():
|
||||||
c = Cursor()
|
c = Cursor()
|
||||||
ctypes.windll.user32.GetCursorPos(ctypes.byref(c))
|
fn = _api('user32', 'GetCursorPos', wintypes.BOOL, [ctypes.POINTER(Cursor)])
|
||||||
|
if not fn(ctypes.byref(c)):
|
||||||
|
raise OSError('GetCursorPos 失败')
|
||||||
return (c.x, c.y)
|
return (c.x, c.y)
|
||||||
|
|
||||||
|
|
||||||
def foreground_window():
|
def foreground_window():
|
||||||
return ctypes.windll.user32.GetForegroundWindow()
|
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():
|
def has_foreground():
|
||||||
"""当前会话有没有可接收输入的前台窗口。
|
"""当前是否存在前台窗口; 激活切换时也可能短暂为 0。"""
|
||||||
|
|
||||||
RDP 会话里常常是 0 —— 那种情况下所有注入(键盘尤其是)都不会生效。
|
|
||||||
"""
|
|
||||||
return bool(foreground_window())
|
return bool(foreground_window())
|
||||||
|
|
||||||
|
|
||||||
def acceleration_on():
|
def acceleration_on():
|
||||||
"""指针加速是否开着。开着就别指望 counts 和像素成线性。"""
|
"""指针加速是否开着。开着就别指望 counts 和像素成线性。"""
|
||||||
a = (ctypes.c_int * 3)()
|
a = (ctypes.c_int * 3)()
|
||||||
ctypes.windll.user32.SystemParametersInfoA(SPI_GETMOUSE, 0, ctypes.byref(a), 0)
|
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])
|
return bool(a[2])
|
||||||
|
|
||||||
|
|
||||||
def mouse_speed():
|
def mouse_speed():
|
||||||
s = ctypes.c_int()
|
s = ctypes.c_int()
|
||||||
ctypes.windll.user32.SystemParametersInfoA(SPI_GETMOUSESPEED, 0, ctypes.byref(s), 0)
|
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
|
return s.value
|
||||||
|
|
||||||
|
|
||||||
@@ -88,8 +117,10 @@ class DriverInput:
|
|||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
self._dll = ctypes.CDLL(self.dll_path)
|
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
|
ok = self._dll.device_open() == 1
|
||||||
except OSError as e:
|
except (OSError, AttributeError) as e:
|
||||||
self.log('[driver] 加载 DLL 失败: %s' % e)
|
self.log('[driver] 加载 DLL 失败: %s' % e)
|
||||||
self._dll = None
|
self._dll = None
|
||||||
return False
|
return False
|
||||||
@@ -106,13 +137,16 @@ class DriverInput:
|
|||||||
"""返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。"""
|
"""返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。"""
|
||||||
if not self.open():
|
if not self.open():
|
||||||
return False, '罗技驱动不可用(device_open 失败)'
|
return False, '罗技驱动不可用(device_open 失败)'
|
||||||
if not has_foreground():
|
try:
|
||||||
return False, ('当前会话没有前台窗口(GetForegroundWindow=0) —— '
|
if not is_console_session():
|
||||||
'多半是 RDP 独立会话, 驱动级输入在这类会话里不生效, '
|
return False, '当前进程不在物理 console 会话, 不启用驱动输入'
|
||||||
'需要物理 console 会话')
|
if not has_foreground():
|
||||||
if acceleration_on():
|
return False, '当前会话没有前台窗口(GetForegroundWindow=0), 暂不启用驱动输入'
|
||||||
return False, ('指针加速开着, counts 与像素不成比例, 定位会不准 —— '
|
if acceleration_on():
|
||||||
'关掉"提高指针精确度"后重试')
|
return False, ('指针加速开着, counts 与像素不成比例, 定位会不准 —— '
|
||||||
|
'关掉"提高指针精确度"后重试')
|
||||||
|
except (OSError, AttributeError) as e:
|
||||||
|
return False, '无法确认输入环境: %s' % e
|
||||||
return True, 'ok'
|
return True, 'ok'
|
||||||
|
|
||||||
# ---------------------------------------------------------------- 移动
|
# ---------------------------------------------------------------- 移动
|
||||||
@@ -160,9 +194,11 @@ class DriverInput:
|
|||||||
% (sx, sy, cx, cy))
|
% (sx, sy, cx, cy))
|
||||||
return False
|
return False
|
||||||
for _ in range(int(times)):
|
for _ in range(int(times)):
|
||||||
self._dll.mouse_down(1)
|
try:
|
||||||
time.sleep(0.03)
|
self._dll.mouse_down(1)
|
||||||
self._dll.mouse_up(1)
|
time.sleep(0.03)
|
||||||
|
finally:
|
||||||
|
self._dll.mouse_up(1)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def key_down(self, key):
|
def key_down(self, key):
|
||||||
@@ -180,7 +216,11 @@ class DriverInput:
|
|||||||
|
|
||||||
def client_to_screen(hwnd, x, y):
|
def client_to_screen(hwnd, x, y):
|
||||||
"""游戏客户区坐标 -> 屏幕坐标。"""
|
"""游戏客户区坐标 -> 屏幕坐标。"""
|
||||||
from ctypes import wintypes
|
if not hwnd:
|
||||||
|
raise OSError('没有游戏窗口句柄')
|
||||||
pt = wintypes.POINT(int(x), int(y))
|
pt = wintypes.POINT(int(x), int(y))
|
||||||
ctypes.windll.user32.ClientToScreen(hwnd, ctypes.byref(pt))
|
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)
|
return (pt.x, pt.y)
|
||||||
|
|||||||
Reference in New Issue
Block a user