diff --git a/lc_mcp/aalc_patches.py b/lc_mcp/aalc_patches.py index 178f190..67f6eae 100644 --- a/lc_mcp/aalc_patches.py +++ b/lc_mcp/aalc_patches.py @@ -202,4 +202,57 @@ def install_driver_click(auto, screen, driver=None, log=print): if hasattr(proxy, name): setattr(auto, name, getattr(proxy, name)) log('[lc_mcp] patch: 鼠标点击已切到罗技驱动级输入') - return drv \ No newline at end of file + return drv +# ---------------------------------------------------------------- 前台窗口健壮化 + +def install_robust_set_foreground(screen, log=print): + """把 SetForegroundWindow 换成带 AttachThreadInput 兜底的版本。 + + 背景(2026-10-22): cfg.background_click=False 时 screen.py:342 会调 + self.handle.setForeground(), 而原生实现只有一句裸调用 + win32gui.SetForegroundWindow(hwnd)。Windows 不允许非前台进程抢占前台, + 失败时抛 pywintypes.error(0, 'SetForegroundWindow', ...) —— 这个异常在 + set_win() 里没有捕获, 直接把任务带崩(观测: exit code 3 之前的 traceback)。 + + 兜底手法是 MSDN 认可的标准做法: 把自己的线程输入队列挂到当前前台窗口的 + 线程上, 借它的前台权限完成切换, 完成后解挂。 + """ + handle = getattr(screen, 'handle', None) + if handle is None or not hasattr(handle, 'setForeground'): + log('[lc_mcp] 前台窗口补丁跳过: screen.handle 没有 setForeground') + return None + + original = handle.setForeground + + def setForeground(): + hwnd = getattr(handle, 'hwnd', 0) + if not hwnd: + return + try: + original() + return + except Exception: + pass # 落到下面的 AttachThreadInput 兜底 + try: + import win32api + import win32gui + import win32process + + foreground = win32gui.GetForegroundWindow() + thread_fg = win32process.GetWindowThreadProcessId(foreground)[0] if foreground else 0 + thread_me = win32api.GetCurrentThreadId() + attached = False + if thread_fg and thread_fg != thread_me: + attached = bool(win32process.AttachThreadInput(thread_fg, thread_me, True)) + try: + win32gui.BringWindowToTop(hwnd) + win32gui.SetForegroundWindow(hwnd) + finally: + if attached: + win32process.AttachThreadInput(thread_fg, thread_me, False) + except Exception as e: + log('[lc_mcp] setForeground 兜底也失败: %s: %s' % (type(e).__name__, e)) + + handle.setForeground = setForeground + log('[lc_mcp] patch: SetForegroundWindow 加 AttachThreadInput 兜底') + return handle \ No newline at end of file diff --git a/lc_mcp/aalc_task.py b/lc_mcp/aalc_task.py index 1d9c275..f19f67b 100644 --- a/lc_mcp/aalc_task.py +++ b/lc_mcp/aalc_task.py @@ -11,7 +11,8 @@ import sys from . import preflight from .aalc_engine import bootstrap -from .aalc_patches import WindowGuard, install_driver_click, install_exact_team_match +from .aalc_patches import (WindowGuard, install_driver_click, install_exact_team_match, + install_robust_set_foreground) # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效 TASKS = { @@ -82,6 +83,7 @@ def run(task, params): return PREFLIGHT_EXIT install_exact_team_match(auto, log) + install_robust_set_foreground(screen, log=log) guard = WindowGuard(screen, cfg, log=log) guard.start() restore_path = os.environ.get(RESTORE_ENV)