| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625 |
- using System;
- using System.Collections.Generic;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- using BeiJingComService.Infrastructure;
- namespace BeiJingComService.Core
- {
- /// <summary>
- /// COM 弹框置顶(Round57):让首信医保 COM 自己弹出的对话框始终显示在所有窗口最前。
- ///
- /// 背景:COM 调用跑在 <see cref="ComGateway"/> 的 STA 工作线程上,宿主是托盘进程
- /// (主窗体最小化 + ShowInTaskbar=false),进程没有前台窗口。COM 以 hwndParent=0 弹的
- /// 模态框会被系统排到当前前台窗口(HIS / prBrowser)后面,操作员看不见;而模态框又堵着
- /// STA 线程,直到有人点掉 —— 没人点就一路等到 ComTimeoutMs(60 秒)超时,结果作废,
- /// 后续每一笔调用继续排队干等。
- ///
- /// 两条路并行,互为兜底:
- /// A. 线程级 WH_CBT 钩子:在 ComGatewayWorker 线程上装,窗口激活瞬间就置顶(零延迟)。
- /// B. 进程级看门狗:独立后台线程,仅在一笔 COM 调用在飞期间每 ComDialogTopmostWatchMs
- /// 扫一遍本进程窗口。兜住「COM 自己另起线程弹框」这类钩子抓不到的情况。
- ///
- /// 五条硬约束(改动前请先读):
- /// 1. 钩子委托必须 static 持有,否则被 GC 回收后系统回调野指针,随机崩溃;
- /// 2. 钩子回调里<b>绝不抛异常</b>,且无条件 CallNextHookEx —— 它是在 COM 的窗口
- /// 创建/激活流程中间被调用的,异常穿出去会打断对方流程;
- /// 3. 钩子回调里<b>零 I/O</b>(不写日志、不碰文件),只累加计数;日志由看门狗线程事后落;
- /// 4. 看门狗必须是自己的线程,绝不能放 UI 线程 —— 跨线程 SetWindowPos 要等目标线程
- /// 泵消息,万一被拖住会连带假死诊断面板和托盘菜单;
- /// 5. 判据不能用窗口类名 "#32770" 当主判据:那只是 Win32 标准对话框的类名,
- /// 首信是 VB6 系,自绘窗体类名是 ThunderRT6FormDC,用 #32770 会漏一半。
- /// 本实现用「本进程 + 顶层 + 有标题栏」,类名只作可选的收窄条件。
- ///
- /// 失败代价:任何一步失败都只写日志,不影响读卡与交易,最坏等于回到 1.0.0.3。
- /// </summary>
- internal static class DialogTopmostWatcher
- {
- // ===================== 常量 =====================
- private const int WH_CBT = 5;
- private const int HCBT_ACTIVATE = 5;
- private const int GWL_STYLE = -16;
- private const int GWL_EXSTYLE = -20;
- private const int WS_CHILD = 0x40000000;
- private const int WS_CAPTION = 0x00C00000;
- private const int WS_EX_TOPMOST = 0x00000008;
- private const uint SWP_NOSIZE = 0x0001;
- private const uint SWP_NOMOVE = 0x0002;
- private const uint SWP_NOACTIVATE = 0x0010;
- private const uint SWP_NOOWNERZORDER = 0x0200;
- private const uint FLASHW_ALL = 0x00000003;
- private const uint FLASHW_TIMERNOFG = 0x0000000C;
- /// <summary>本服务自身的 WinForms 窗体类名前缀,看门狗要排除掉(托盘窗、诊断面板)。</summary>
- private const string OWN_WINFORMS_CLASS_PREFIX = "WindowsForms10";
- // ===================== 状态 =====================
- private static readonly object _sync = new object();
- /// <summary>钩子回调委托:必须 static 持有,防止被 GC 回收(钩子最经典崩溃点)。</summary>
- private static readonly CbtProc _proc = HookCallback;
- /// <summary>EnumWindows 回调委托,同样 static 持有。</summary>
- private static readonly EnumWindowsProc _enumProc = EnumWindowCallback;
- private static IntPtr _hook = IntPtr.Zero;
- private static int _hookThreadId;
- /// <summary>是否有一笔 COM 调用在飞(1=是)。钩子与看门狗都以它为前提。</summary>
- private static int _inCall;
- private static long _appliedCount;
- private static Thread _dog;
- private static volatile bool _dogRunning;
- private readonly static List<IntPtr> _found = new List<IntPtr>(8);
- /// <summary>只用于「避免同一个句柄重复写日志」,不参与是否置顶的判定。</summary>
- private static readonly HashSet<IntPtr> _logged = new HashSet<IntPtr>();
- private static readonly uint _currentPid = GetCurrentProcessId();
- // 配置(首次安装时读一次,配置项变更需重启程序)
- private static bool _configLoaded;
- private static bool _enabled = true;
- private static int _watchMs = 200;
- private static bool _foreground;
- private static string[] _classFilter;
- // ===================== 对外接口 =====================
- /// <summary>钩子是否已装上(供 /health 展示)。</summary>
- public static bool IsHookInstalled
- {
- get { return _hook != IntPtr.Zero; }
- }
- /// <summary>累计置顶次数(钩子 + 看门狗)。</summary>
- public static long TopmostAppliedCount
- {
- get { return Interlocked.Read(ref _appliedCount); }
- }
- /// <summary>是否有一笔 COM 调用在执行。</summary>
- public static bool IsCallInFlight
- {
- get { return Volatile.Read(ref _inCall) == 1; }
- }
- /// <summary>
- /// 在<b>当前线程</b>上装 WH_CBT 钩子。
- /// 必须由 ComGateway 的 STA 工作线程在线程体内调用(WorkerLoop 第一行),
- /// 装在外层 StartWorker() 里等于装在调用方线程上,收不到弹框事件。
- /// </summary>
- public static void InstallForCurrentThread()
- {
- try
- {
- EnsureConfig();
- if (!_enabled)
- {
- Logger.Info("COM 弹框置顶已关闭(ComDialogTopmost=false),不装钩子、不起看门狗");
- return;
- }
- // 服务模式(--service)跑在 Session 0:弹框不在用户桌面,SetWindowPos 无处可施
- if (!Environment.UserInteractive)
- {
- Logger.Info("非交互式会话(--service / Session 0),COM 弹框不在用户桌面,跳过置顶钩子");
- return;
- }
- if (_hook != IntPtr.Zero) return;
- _hook = SetWindowsHookEx(WH_CBT, _proc, GetModuleHandle(null), GetCurrentThreadId());
- if (_hook == IntPtr.Zero)
- {
- Logger.Error("COM 弹框置顶钩子安装失败,Win32 错误码=" + Marshal.GetLastWin32Error()
- + ",本次运行不置顶(不影响读卡)");
- return;
- }
- _hookThreadId = (int)GetCurrentThreadId();
- Logger.Info("COM 弹框置顶钩子已安装,线程=" + _hookThreadId
- + ",看门狗间隔=" + _watchMs + "ms"
- + ",抢前台=" + (_foreground ? "是" : "否")
- + ",类名过滤=" + (_classFilter == null || _classFilter.Length == 0 ? "不限" : string.Join(",", _classFilter)));
- if (_watchMs > 0) StartDog();
- }
- catch (Exception ex)
- {
- Logger.Error("安装 COM 弹框置顶钩子异常(已忽略,不影响读卡)", ex);
- }
- }
- /// <summary>摘钩子、停看门狗。工作线程退出前调用。</summary>
- public static void Uninstall()
- {
- try
- {
- StopDog();
- if (_hook != IntPtr.Zero)
- {
- UnhookWindowsHookEx(_hook);
- _hook = IntPtr.Zero;
- Logger.Info("COM 弹框置顶钩子已摘除,累计置顶 " + TopmostAppliedCount + " 次");
- }
- }
- catch (Exception ex)
- {
- Logger.Error("摘除 COM 弹框置顶钩子异常(已忽略)", ex);
- }
- }
- /// <summary>一笔 COM 调用开始:允许钩子/看门狗工作。</summary>
- public static void BeginCall()
- {
- Interlocked.Exchange(ref _inCall, 1);
- }
- /// <summary>一笔 COM 调用结束:停掉看门狗扫描(钩子本身不动,等下次弹框)。</summary>
- public static void EndCall()
- {
- Interlocked.Exchange(ref _inCall, 0);
- // 清掉「已记过日志」的句柄集合:句柄会被系统复用,不清会把新弹框的日志误吞掉
- lock (_sync)
- {
- _logged.Clear();
- }
- }
- // ===================== 钩子(A 路) =====================
- private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
- {
- try
- {
- // HCBT_ACTIVATE:窗口即将被激活。此刻 SetWindowPos 有效;
- // HCBT_CREATEWND 阶段窗口还没真正创建,改 z 序会失败,故不用它。
- //
- // ★ 这里刻意不判 _inCall:钩子是线程级的,只看得见 ComGatewayWorker 这个
- // COM 线程创建的窗口,本来就都是 COM 的弹框。而「队列空闲后自动 close」
- // 那条路径不经过 CallNative,判 _inCall 会漏掉它在关闭时弹的框。
- if (nCode >= 0 && wParam == (IntPtr)HCBT_ACTIVATE)
- {
- IntPtr hwnd = lParam;
- if (hwnd != IntPtr.Zero && IsTargetWindow(hwnd))
- {
- // 回调里零 I/O:只做 SetWindowPos + 计数,日志交给看门狗线程
- ApplyTopmost(hwnd, false);
- }
- }
- }
- catch
- {
- // ★ 绝不能抛出去:这里处于 COM 的窗口激活流程中间
- }
- return CallNextHookEx(_hook, nCode, wParam, lParam);
- }
- // ===================== 看门狗(B 路) =====================
- private static void StartDog()
- {
- lock (_sync)
- {
- if (_dog != null) return;
- _dogRunning = true;
- _dog = new Thread(DogLoop);
- _dog.IsBackground = true;
- _dog.Name = "ComTopmostDog";
- _dog.Start();
- }
- }
- private static void StopDog()
- {
- Thread dog;
- lock (_sync)
- {
- _dogRunning = false;
- dog = _dog;
- _dog = null;
- }
- if (dog != null && dog.IsAlive)
- {
- try { dog.Join(TimeSpan.FromSeconds(1)); }
- catch (Exception ex) { Logger.Error("等待弹框置顶看门狗退出超时", ex); }
- }
- }
- private static void DogLoop()
- {
- while (_dogRunning)
- {
- try
- {
- if (Volatile.Read(ref _inCall) == 1) ScanAndApply();
- }
- catch (Exception ex)
- {
- // 看门狗失败只要记一次日志继续跑,不影响业务
- Logger.Error("弹框置顶看门狗扫描失败(已忽略)", ex);
- }
- // 分片睡眠:保证 StopDog 能在 1 秒内退出
- int wait = _watchMs > 0 ? _watchMs : 200;
- for (int slept = 0; slept < wait && _dogRunning; slept += 50)
- {
- Thread.Sleep(Math.Min(50, wait - slept));
- }
- }
- }
- private static void ScanAndApply()
- {
- _found.Clear();
- EnumWindows(_enumProc, IntPtr.Zero);
- if (_found.Count == 0) return;
- for (int i = 0; i < _found.Count; i++)
- {
- ApplyTopmost(_found[i], true);
- }
- }
- private static bool EnumWindowCallback(IntPtr hwnd, IntPtr lParam)
- {
- try
- {
- if (hwnd == IntPtr.Zero) return true;
- if (!IsWindowVisible(hwnd)) return true;
- uint pid;
- GetWindowThreadProcessId(hwnd, out pid);
- if (pid != _currentPid) return true;
- if (IsTargetWindow(hwnd)) _found.Add(hwnd);
- }
- catch
- {
- // 单个窗口判断失败不影响整轮扫描
- }
- return true;
- }
- // ===================== 判定与执行 =====================
- /// <summary>
- /// 是否属于「要置顶的弹框」:
- /// 1. 顶层窗口(无 WS_CHILD);
- /// 2. 有标题栏(WS_CAPTION)—— 顺带排掉 tooltip、IME 候选窗、拖动小窗;
- /// 3. 不是本服务自己的 WinForms 窗体(托盘窗、诊断面板);
- /// 4. 类名不在可选白名单外(白名单为空表示不限);
- /// 5. 目前还不是 topmost(已经是就不用再动,也顺便防了反复调用)。
- /// </summary>
- private static bool IsTargetWindow(IntPtr hwnd)
- {
- int style = GetStyle(hwnd);
- if ((style & WS_CHILD) != 0) return false;
- if ((style & WS_CAPTION) != WS_CAPTION) return false;
- string cls = GetClassNameSafe(hwnd);
- if (cls.Length > 0 && cls.StartsWith(OWN_WINFORMS_CLASS_PREFIX, StringComparison.Ordinal))
- {
- return false;
- }
- if (_classFilter != null && _classFilter.Length > 0)
- {
- bool hit = false;
- for (int i = 0; i < _classFilter.Length; i++)
- {
- if (string.Equals(cls, _classFilter[i], StringComparison.OrdinalIgnoreCase))
- {
- hit = true;
- break;
- }
- }
- if (!hit) return false;
- }
- if ((GetExStyle(hwnd) & WS_EX_TOPMOST) != 0) return false;
- return true;
- }
- private static void ApplyTopmost(IntPtr hwnd, bool fromDog)
- {
- try
- {
- if (!IsWindow(hwnd)) return;
- bool wasTopmost = (GetExStyle(hwnd) & WS_EX_TOPMOST) != 0;
- SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
- SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
- if (_foreground)
- {
- TryActivate(hwnd);
- }
- else if (!wasTopmost)
- {
- // 默认不抢焦点,只闪任务栏/标题栏提醒(RDP 下通常只闪任务栏,属正常)
- Flash(hwnd);
- }
- Interlocked.Increment(ref _appliedCount);
- // 钩子路径(fromDog=false)不落盘:CBT 钩子是串行的,写文件会拖住 COM 的窗口激活
- if (fromDog && !wasTopmost) LogApplied(hwnd);
- }
- catch (Exception ex)
- {
- if (fromDog) Logger.Error("弹框置顶失败(已忽略)", ex);
- }
- }
- /// <summary>同一个句柄只记一次日志,避免看门狗 200ms 一轮刷屏。</summary>
- private static void LogApplied(IntPtr hwnd)
- {
- bool first;
- lock (_sync)
- {
- first = _logged.Add(hwnd);
- }
- if (!first) return;
- Logger.Info("[Topmost] 已置顶 hwnd=0x" + hwnd.ToInt64().ToString("X")
- + " class=" + GetClassNameSafe(hwnd)
- + " title=" + GetWindowTextSafe(hwnd)
- + "(累计 " + TopmostAppliedCount + " 次)");
- }
- /// <summary>
- /// 抢前台(仅 ComDialogForeground=true 时调用)。前后台锁定下这招不是 100% 生效,
- /// 失败就失败,不影响置顶本身。
- /// </summary>
- private static void TryActivate(IntPtr hwnd)
- {
- try
- {
- uint pid;
- IntPtr fg = GetForegroundWindow();
- uint fgThread = fg == IntPtr.Zero ? 0 : GetWindowThreadProcessId(fg, out pid);
- uint curThread = GetCurrentThreadId();
- if (fgThread == 0 || fgThread == curThread)
- {
- SetForegroundWindow(hwnd);
- return;
- }
- if (AttachThreadInput(curThread, fgThread, true))
- {
- try { SetForegroundWindow(hwnd); }
- finally { AttachThreadInput(curThread, fgThread, false); }
- }
- }
- catch
- {
- // 抢前台失败无所谓,置顶已经生效
- }
- }
- private static void Flash(IntPtr hwnd)
- {
- try
- {
- var fi = new FLASHWINFO
- {
- cbSize = (uint)Marshal.SizeOf(typeof(FLASHWINFO)),
- hwnd = hwnd,
- dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG,
- uCount = 3,
- dwTimeout = 0
- };
- FlashWindowEx(ref fi);
- }
- catch
- {
- // 闪烁失败无所谓
- }
- }
- // ===================== 配置 =====================
- private static void EnsureConfig()
- {
- if (_configLoaded) return;
- _configLoaded = true;
- try
- {
- _enabled = AppConfig.ComDialogTopmost;
- _watchMs = AppConfig.ComDialogTopmostWatchMs;
- _foreground = AppConfig.ComDialogForeground;
- _classFilter = ParseClasses(AppConfig.ComDialogTopmostClasses);
- if (_watchMs < 0) _watchMs = 0;
- }
- catch (Exception ex)
- {
- // 配置写坏也不能让钩子把网关带崩:按默认值启用
- _enabled = true;
- _watchMs = 200;
- _foreground = false;
- _classFilter = null;
- Logger.Error("读取 COM 弹框置顶配置失败,按默认值(启用 + 看门狗 200ms)处理", ex);
- }
- }
- private static string[] ParseClasses(string raw)
- {
- if (string.IsNullOrWhiteSpace(raw)) return null;
- string[] parts = raw.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
- var list = new List<string>(parts.Length);
- for (int i = 0; i < parts.Length; i++)
- {
- string item = parts[i].Trim();
- if (item.Length > 0) list.Add(item);
- }
- return list.Count == 0 ? null : list.ToArray();
- }
- // ===================== 辅助 =====================
- private static int GetStyle(IntPtr hwnd)
- {
- return IntPtr.Size == 8
- ? (int)GetWindowLongPtr(hwnd, GWL_STYLE).ToInt64()
- : GetWindowLong(hwnd, GWL_STYLE);
- }
- private static int GetExStyle(IntPtr hwnd)
- {
- return IntPtr.Size == 8
- ? (int)GetWindowLongPtr(hwnd, GWL_EXSTYLE).ToInt64()
- : GetWindowLong(hwnd, GWL_EXSTYLE);
- }
- private static string GetClassNameSafe(IntPtr hwnd)
- {
- try
- {
- var sb = new StringBuilder(256);
- int n = GetClassName(hwnd, sb, sb.Capacity);
- return n > 0 ? sb.ToString(0, n) : string.Empty;
- }
- catch
- {
- return string.Empty;
- }
- }
- private static string GetWindowTextSafe(IntPtr hwnd)
- {
- try
- {
- var sb = new StringBuilder(256);
- int n = GetWindowText(hwnd, sb, sb.Capacity);
- return n > 0 ? sb.ToString(0, n) : string.Empty;
- }
- catch
- {
- return string.Empty;
- }
- }
- // ===================== P/Invoke =====================
- private delegate IntPtr CbtProc(int nCode, IntPtr wParam, IntPtr lParam);
- private delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
- [StructLayout(LayoutKind.Sequential)]
- private struct FLASHWINFO
- {
- public uint cbSize;
- public IntPtr hwnd;
- public uint dwFlags;
- public uint uCount;
- public uint dwTimeout;
- }
- private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
- [DllImport("user32.dll", SetLastError = true)]
- private static extern IntPtr SetWindowsHookEx(int idHook, CbtProc lpfn, IntPtr hMod, uint dwThreadId);
- [DllImport("user32.dll", SetLastError = true)]
- private static extern bool UnhookWindowsHookEx(IntPtr hhk);
- [DllImport("user32.dll")]
- private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
- [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
- private static extern IntPtr GetModuleHandle(string lpModuleName);
- [DllImport("kernel32.dll")]
- private static extern uint GetCurrentThreadId();
- [DllImport("kernel32.dll")]
- private static extern uint GetCurrentProcessId();
- [DllImport("user32.dll")]
- private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
- [DllImport("user32.dll", SetLastError = true)]
- private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
- int X, int Y, int cx, int cy, uint uFlags);
- [DllImport("user32.dll", EntryPoint = "GetWindowLong")]
- private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
- [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr")]
- private static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex);
- [DllImport("user32.dll", CharSet = CharSet.Unicode)]
- private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
- [DllImport("user32.dll", CharSet = CharSet.Unicode)]
- private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
- [DllImport("user32.dll")]
- private static extern bool IsWindowVisible(IntPtr hWnd);
- [DllImport("user32.dll")]
- private static extern bool IsWindow(IntPtr hWnd);
- [DllImport("user32.dll")]
- private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
- [DllImport("user32.dll")]
- private static extern IntPtr GetForegroundWindow();
- [DllImport("user32.dll")]
- private static extern bool SetForegroundWindow(IntPtr hWnd);
- [DllImport("user32.dll")]
- private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
- [DllImport("user32.dll")]
- private static extern bool FlashWindowEx(ref FLASHWINFO pwfi);
- }
- }
|