diff --git a/docs/代码导览.md b/docs/代码导览.md
new file mode 100644
index 0000000..770f50a
--- /dev/null
+++ b/docs/代码导览.md
@@ -0,0 +1,124 @@
+# 代码导览(接手必读)
+
+> 目的:拿到这份代码的人,能在几分钟内知道**哪个功能在哪个文件**、**改动要动哪里**、**哪些地方有坑**。
+>
+> 项目:.NET Framework 4.8 + WinForms,只读的 Windows UI 自动化检查/监控工具。
+> 解决方案:`pacs_win_uia.sln`(主工程 `src/pacs_win_uia`,测试夹具 `tests/uia-fixture`,回归测试 `tests/regression`)。
+
+---
+
+## 一、一分钟建立全局印象
+
+```
+Program.cs 进程入口
+ ├─ 无参数 → 单实例:第一个进程当 owner 并开 MainForm,后面的进程把请求转发给它
+ └─ --read-saved/-config → 无界面读取(也可以被转发到正在运行的 GUI 实例里执行)
+
+MainForm(UI/MainForm.cs) 三栏主界面:窗口列表 | 控件树/列表结果 | 属性 + 控件监控列表
+ ├─ 窗口列表 NativeWindowService(Win32 枚举)
+ ├─ 控件树 ControlTreeService → UIA / MSAA / Win32 三个来源
+ ├─ 路径与定位 ControlPath(XPath)+ ControlLocatorService(回读)
+ ├─ 控件监控列表 ControlMonitorEditorControl → ControlMonitorStore(JSON)
+ ├─ 悬浮条 FloatingBarManager + FloatingToolbarForm
+ └─ 拾取控件 CrosshairPicker + TargetProbeService + PickerOverlayForm
+```
+
+数据流(最重要的一条):
+
+```
+窗口(PID/类名/标题) → 控件树快照(ControlTreeNode) → XPath 路径(ControlPath)
+ ↓
+ 监控项 JSON(只存稳定定位信息)
+ ↓
+ 回读:重新读树 → XPath 求值 → 唯一命中 → 读值/画框
+```
+
+**核心原则**(改代码前请先接受这四条,否则很容易改出"看起来能用但定位到错控件"的 bug):
+
+1. **找不准就说找不到**。XPath 多处命中、树读取不完整、路径语法不对,一律明确报错,绝不"取第一个"。
+2. **动态的东西不落盘**。RuntimeId、实时值、焦点状态、会变的 Name 都不写进长期配置。
+3. **跨进程调用可能永久卡住**。任何 UIA/MSAA 调用都要有预算(`ReadBudget`)、独立线程和取消,不能占 UI 线程。
+4. **只读**。不注入、不改目标、不点击目标控件(连拾取时的鼠标左键都用低级钩子吞掉)。
+
+---
+
+## 二、"我要改 X,看哪个文件"
+
+| 我想改… | 主要文件 | 备注 |
+|---|---|---|
+| 主界面布局/按钮/三栏比例 | `UI/MainForm.cs` | 布局自检 `VerifyLayout()` 会报错,改动后看日志 |
+| 控件树怎么显示、要不要闪烁 | `UI/ControlTreeReconciler.cs` | 增量更新,绝不清空重建 |
+| 控件树读取来源与顺序 | `Services/ControlTreeService.cs` | Auto = UIA → MSAA → Win32 |
+| UIA 快照/缓存/Pattern | `Services/UiAutomationService.cs` | 统一 RawView + CacheRequest |
+| 列表读取(行列/单元格/降级) | `Services/ListReaderService.cs` | 最长的文件,见其顶部导览 |
+| 取值(Name/Value/Text/选中/焦点/OCR) | `Services/ControlValueReader.cs` | valueKey 的语义都在这里 |
+| Path(XPath)生成与求值 | `Services/ControlPath.cs` | **定位核心**,改这里影响全局 |
+| 保存路径时的字段与校验 | `Services/ControlLocatorBuilder.cs` | 与回读共用匹配逻辑 |
+| 回读定位(含窗口匹配) | `Services/ControlLocatorService.cs` | 唯一命中才返回 |
+| 监控项 JSON 读写 | `Services/ControlMonitorStore.cs` | 加载宽松、保存严格 |
+| 监控列表 UI/编辑/定位 | `UI/ControlMonitorEditorControl.cs` | Path 可 F2 编辑、双击多行编辑 |
+| 设置界面 | `UI/SettingsForm.cs` | 各页保存到 `AppSettings` |
+| 设置的默认值与兼容 | `Models/AppSettings.cs` | `Normalize()` 是兼容旧 JSON 的地方 |
+| 悬浮条的显示条件/跟随 | `Services/FloatingBarManager.cs` | 见下面"悬浮条规则" |
+| 悬浮条外观(自绘/透明) | `UI/FloatingToolbarForm.cs` | layered window,注意 GDI 释放 |
+| 遮挡/可见性判断 | `Services/WindowVisibility.cs` | 两个 API 用途不同,见文件头 |
+| 高亮框/跟随 | `Services/HighlightFollower.cs` | 跟随锚点窗口的相对偏移 |
+| 全部控件框绘制 | `UI/NodeMapOverlayForm.cs` | 只在前台窗口且未遮挡处绘制 |
+| 拾取器 | `Picker/CrosshairPicker.cs` + `UI/PickerOverlayForm.cs` | 不抢焦点、吞左键 |
+| 单实例/转发 | `Services/SingleInstanceService.cs` + `Program.cs` | Mutex + 命名管道 |
+| 无界面读取 | `Services/HeadlessConfigReader.cs` | 每条独立计时,统计口径在文件头 |
+| 截图 / OCR | `Services/ScreenshotService.cs`、`Services/OcrClient.cs` | OCR 默认关闭 |
+| 命令时机与退出清理 | `Services/CommandRunner.cs`、`Services/ProcessJob.cs` | 退出时结束整棵进程树 |
+| 日志 | `Diagnostics/AppLog.cs` | GUI 启动会自建控制台窗口 |
+
+---
+
+## 三、几条容易踩的坑(都是踩过的)
+
+- **不要在 UI 线程做 UIA/MSAA 调用**:Provider 挂住时界面直接冻结。后台线程 + `ReadBudget` + 序号丢弃旧结果。
+- **不要用会变的显示文本做身份**:控件名可能随患者/文件/语言/计数变化。身份只用 AutomationId / ClassName / RuntimeId(运行期)/ HWND(Win32)。
+- **不要清空重建控件树**:300ms 刷新时清空会闪烁并丢失选择/展开,用 `ControlTreeReconciler`。
+- **不要"取第一个匹配"**:不确定就报错,让人重新拾取。
+- **PropertyGrid 正在编辑时不要去 rebind**:会打断用户输入,`MainForm` 里有专门判断。
+- **悬浮条的"名称"不是定位条件**:定位条件是进程名/窗口类/标题关键词 + 可选导入 XPath。
+- **旧路径格式已停用**:`[Uia] A[id] > B:name`、`Type[id]` 之类不再执行,只保留给人工编辑修正。
+- **本工具自己的窗口不算遮挡**:主界面/设置窗口压住目标不影响悬浮条显示(否则在设置页里根本测不了)。
+- **bin\Debug 的 exe 被运行时锁定**:改完代码要编译时,先关掉正在运行的工具,或编译到别的输出目录。
+
+---
+
+## 四、悬浮条显示规则(当前版本)
+
+只有**同时**满足下面条件才会显示:
+
+1. 悬浮条 `Enabled = true`,且至少有一个启用的按钮;
+2. 窗口条件(进程名 / 窗口类 / 标题关键词)已填写的部分**全部**满足,且**唯一**匹配到一个窗口;
+ - 匹配时**优先选可见窗口**,跳过 UWP 留下的最小化同名框架窗口;
+3. 如果导入了监控项 XPath,该 XPath 在该窗口里**唯一命中**;
+4. 勾选了"窗口可见且未被遮挡时才显示"时:锚定窗口存在、可见、未最小化,且**没有被别的程序完全遮住**(部分遮挡不影响;本工具自己的窗口一律忽略)。
+
+检测结果显示"当前不显示"时,会说明卡在哪一步,并在被外部程序遮挡时点名是哪个窗口。
+
+---
+
+## 五、测试与验证
+
+- 回归测试(纯内存,不需要目标程序):
+ ```
+ dotnet msbuild tests\regression\RegressionTests.csproj -t:Build -p:Configuration=Debug -v:minimal
+ tests\regression\bin\Debug\RegressionTests.exe
+ ```
+ 想同时保留正在运行的工具实例时,加 `-p:OutputPath=<临时目录>\` 编译到别处再运行。
+- 跨进程手工夹具:`tests\run-fixture.cmd`(见 `tests/README.md`)。
+- **重要**:不要在本进程里用 UIA 读本工具自己的窗口,会原生崩溃。验证 UIA 逻辑必须用独立进程的夹具。
+- 真机验收清单:控件树内容、拾取后树一致、列表读取行列、Path 往返(复制→按 path 定位)、
+ 监控项保存后无界面 `--read-saved` 命中、悬浮条按条件显示/隐藏、遮挡/最小化行为。
+
+---
+
+## 六、想要继续开发,建议的顺序
+
+1. 先跑一次界面 + 回归测试,确认基线正常;
+2. 改一个功能点,同时补一条回归用例(`tests/regression` 里新增 `Register` 项);
+3. 涉及跨进程读取的改动,用独立夹具实测,不要只看编译通过;
+4. 改完在 `TODO.md` 记录"已验证 / 未验证",未在真实 PACS 上测过的不要写成已完成。
diff --git a/src/pacs_win_uia/Diagnostics/AppLog.cs b/src/pacs_win_uia/Diagnostics/AppLog.cs
index 0810d66..9d18ff1 100644
--- a/src/pacs_win_uia/Diagnostics/AppLog.cs
+++ b/src/pacs_win_uia/Diagnostics/AppLog.cs
@@ -1,3 +1,27 @@
+// =============================================================================
+// AppLog.cs —— 控制台日志(字段诊断用),永不抛异常、永不阻塞 UI
+//
+// 职责:
+// 把日志写到控制台。写失败绝不能影响工具运行,因此所有写入都是 best-effort。
+//
+// 被谁调用:
+// Program.Main 调用 AppLog.Init();全项目通过 AppLog.Info/Warn/Error/Debug 记录。
+//
+// 控制台准备策略(PrepareConsole):
+// 1) 已有控制台窗口:重定向标准流即可。
+// 2) 有可用的标准输出(管道/重定向,如 Git Bash、IDE 捕获):直接用它,不动。
+// 3) 附着到父进程控制台(从终端启动)。
+// 4) 双击启动:自建一个控制台窗口,让日志可见。
+// 注意:带管道时 AllocConsole 会因 ACCESS_DENIED 失败(已存在伪控制台),故先判断标准输出。
+//
+// 注意:
+// 保留控制台自身编码,不强制 UTF-8(否则 GBK 控制台里的中文会乱码)。
+// 关闭日志窗口不会结束工具(吞掉 CTRL_CLOSE_EVENT)。
+//
+// 要改什么就改哪里:
+// 日志级别门限 -> _minimumLevel / MinimumLevel。
+// 控制台准备 -> PrepareConsole。
+// =============================================================================
using System;
using System.IO;
using System.Text;
@@ -5,37 +29,51 @@ using pacs_win_uia.Interop;
namespace pacs_win_uia.Diagnostics
{
+ // 日志级别(数值越大越严重)。
public enum LogLevel
{
+ // 调试细节。
Debug,
+ // 常规信息。
Info,
+ // 警告(不中断功能)。
Warn,
+ // 错误。
Error
}
+ // 静态控制台日志器:写入失败不影响工具运行,也不阻塞 UI。
///
/// Console logger for field diagnostics. Logging never throws and never blocks the UI:
/// a failure to write must not be able to break the tool.
///
public static class AppLog
{
+ // 保护控制台准备与写入的锁。
private static readonly object Sync = new object();
+ // 控制台控制事件的回调委托,需保持引用防止被 GC。
private static NativeMethods.ConsoleCtrlHandler _consoleCtrlHandler;
+ // 控制台是否可用(不可用时所有日志被丢弃)。
private static bool _consoleReady;
+ // 是否已初始化过(Init 幂等)。
private static bool _initialized;
+ // 最低输出级别(低于它的日志被丢弃),默认 Debug。
private static LogLevel _minimumLevel = LogLevel.Debug;
+ // 最低输出级别;低于它的日志不写。
public static LogLevel MinimumLevel
{
get { return _minimumLevel; }
set { _minimumLevel = value; }
}
+ // 控制台当前是否可用。
public static bool ConsoleReady
{
get { return _consoleReady; }
}
+ // 初始化日志:准备控制台、安装控制台控制回调(幂等,可重复调用)。
public static void Init()
{
lock (Sync)
@@ -66,36 +104,43 @@ namespace pacs_win_uia.Diagnostics
}
}
+ // 写调试日志。
public static void Debug(string message)
{
Write(LogLevel.Debug, message, null);
}
+ // 写信息日志。
public static void Info(string message)
{
Write(LogLevel.Info, message, null);
}
+ // 写警告日志。
public static void Warn(string message)
{
Write(LogLevel.Warn, message, null);
}
+ // 写错误日志。
public static void Error(string message)
{
Write(LogLevel.Error, message, null);
}
+ // 写错误日志并附带异常。
public static void Error(string message, Exception exception)
{
Write(LogLevel.Error, message, exception);
}
+ // 写警告日志并附带异常。
public static void Warn(string message, Exception exception)
{
Write(LogLevel.Warn, message, exception);
}
+ // 组装一行日志:级别过滤、拼接消息与异常描述后交给 WriteRaw。
private static void Write(LogLevel level, string message, Exception exception)
{
if (level < _minimumLevel)
@@ -122,6 +167,7 @@ namespace pacs_win_uia.Diagnostics
WriteRaw(level, builder.ToString());
}
+ // 真正写控制台:加时间戳与级别前缀;控制台不可用或写失败时静默丢弃。
private static void WriteRaw(LogLevel level, string message)
{
if (!_consoleReady)
@@ -144,6 +190,7 @@ namespace pacs_win_uia.Diagnostics
}
}
+ // 把异常(含最多 4 层 InnerException)压成一行描述。
private static string DescribeException(Exception exception)
{
var builder = new StringBuilder();
@@ -164,11 +211,13 @@ namespace pacs_win_uia.Diagnostics
return builder.ToString();
}
+ // 描述控制台状态:可用/不可用。
private static string DescribeConsole()
{
return _consoleReady ? "已输出到控制台窗口。" : "当前进程没有可用的控制台,日志已禁用。";
}
+ // 准备控制台(四种策略,见文件顶部);任一成功即返回 true。
private static bool PrepareConsole()
{
if (NativeMethods.GetConsoleWindow() != IntPtr.Zero)
@@ -203,6 +252,7 @@ namespace pacs_win_uia.Diagnostics
return false;
}
+ // 判断是否存在可用的标准输出句柄(管道/重定向场景用它作日志出口)。
private static bool HasUsableStandardOutput()
{
try
@@ -221,6 +271,7 @@ namespace pacs_win_uia.Diagnostics
}
}
+ // 重新打开标准输出写入器,使其指向新附着的控制台;保留控制台编码,不强制 UTF-8。
private static void RedirectStandardStreams()
{
// Console caches its writers on first use; re-open them so output reaches the
@@ -240,6 +291,7 @@ namespace pacs_win_uia.Diagnostics
}
}
+ // 控制台控制事件回调:吞掉关闭事件,避免关闭日志窗口时把工具一起关掉。
private static bool HandleConsoleControl(uint controlType)
{
// Swallow the close/logoff events so closing the log window cannot kill the tool.
diff --git a/src/pacs_win_uia/Interop/MsaaNativeMethods.cs b/src/pacs_win_uia/Interop/MsaaNativeMethods.cs
index 5fd4f73..db9e034 100644
--- a/src/pacs_win_uia/Interop/MsaaNativeMethods.cs
+++ b/src/pacs_win_uia/Interop/MsaaNativeMethods.cs
@@ -1,9 +1,38 @@
+// =============================================================================
+// MsaaNativeMethods.cs —— MSAA/oleacc P/Invoke 与角色/状态常量
+//
+// 职责:
+// 声明 oleacc.dll 的 MSAA 入口,以及把 ROLE_SYSTEM_*/STATE_SYSTEM_* 数值翻成中文名。
+//
+// 被谁调用:
+// 无障碍/控件定位相关代码(读取无障碍对象、角色与状态)使用。
+//
+// 关键点:
+// - IAccessible 接口直接来自框架的 Accessibility 程序集,不手写:手写 vtable/dispid
+// 一旦出错就是访问违例而不是托管的异常。
+// - 四个入口都返回 HRESULT,用 PreserveSig=true 让失败以返回码而非异常呈现,
+// 每个调用点都要检查返回码。
+//
+// 32/64 位注意:
+// 这些是 oleacc 的原生调用;跨位宽进程访问无障碍对象时需保持与目标一致的位宽假设。
+//
+// SAFE 调用约定(重要):
+// - AccessibleChildren 用 object[] + ArraySubType=Struct + SizeParamIndex=2 让封送器
+// 持有 VARIANT 的所有权;手工 IntPtr/VariantClear 会泄漏 COM 引用并崩溃。
+// - WindowFromAccessibleObject 对无窗口对象会成功但 hwnd=NULL,调用方要同时检查
+// HRESULT 与句柄。
+//
+// 要改什么就改哪里:
+// 角色/状态文案 -> BuildRoleNames / BuildStateNames。
+// 新增 MSAA 入口 -> 在 MsaaNativeMethods 中按 PreserveSig=true 追加。
+// =============================================================================
using System;
using System.Runtime.InteropServices;
using Accessibility;
namespace pacs_win_uia.Interop
{
+ // MSAA(oleacc) 入口声明;IAccessible 直接复用框架的 Accessibility 程序集。
///
/// MSAA (oleacc) entry points. The IAccessible interface itself comes from the framework's
/// Accessibility assembly: hand-rolling it means hand-rolling the vtable/dispid layout, and a
@@ -14,13 +43,19 @@ namespace pacs_win_uia.Interop
///
internal static class MsaaNativeMethods
{
+ // 对象 ID:窗口本身。
internal const uint OBJID_WINDOW = 0x00000000;
+ // 对象 ID:客户区。
internal const uint OBJID_CLIENT = 0xFFFFFFFC;
+ // 子对象 ID:自身(而非某个子元素)。
internal const int CHILDID_SELF = 0;
+ // HRESULT:成功。
internal const int S_OK = 0;
+ // IAccessible 的接口 IID,用于 AccessibleObjectFromWindow。
internal static readonly Guid IID_IAccessible = new Guid("618736E0-3C3D-11CF-810C-00AA00389B71");
+ // 从窗口取无障碍对象(hwnd + OBJID_*)。
[DllImport("oleacc.dll", PreserveSig = true)]
internal static extern int AccessibleObjectFromWindow(
IntPtr hwnd,
@@ -28,12 +63,14 @@ namespace pacs_win_uia.Interop
ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] out object ppvObject);
+ // 从屏幕点取无障碍对象(用于点选/命中测试)。
[DllImport("oleacc.dll", PreserveSig = true)]
internal static extern int AccessibleObjectFromPoint(
NativeMethods.POINT ptScreen,
[MarshalAs(UnmanagedType.Interface)] out object ppacc,
[Out, MarshalAs(UnmanagedType.Struct)] out object pvarChild);
+ // 批量读取子对象(封送器负责 VARIANT 生命周期,切勿手工管理 IntPtr/VariantClear)。
///
/// Batched child read. The object[] + ArraySubType=Struct + SizeParamIndex=2 form lets the
/// marshaller own the VARIANTs; manual IntPtr/VariantClear leaks COM references and crashes.
@@ -47,6 +84,7 @@ namespace pacs_win_uia.Interop
object[] rgvarChildren,
out int pcObtained);
+ // 取无障碍对象背后的窗口;无窗口对象会成功返回 hwnd=NULL,需同时检查返回码与句柄。
///
/// Window behind an accessible object. Succeeds with hwnd == NULL for windowless objects,
/// so callers must check both the HRESULT and the handle.
@@ -55,12 +93,16 @@ namespace pacs_win_uia.Interop
internal static extern int WindowFromAccessibleObject(IAccessible pacc, out IntPtr phwnd);
}
+ // ROLE_SYSTEM_* 与 STATE_SYSTEM_* 的名称表(来自 oleacc.h),供界面显示中文。
/// ROLE_SYSTEM_* and STATE_SYSTEM_* names, from oleacc.h.
internal static class MsaaConstants
{
+ // 角色编号 -> 中文名(下标即 ROLE_SYSTEM_* 数值)。
private static readonly string[] RoleNames = BuildRoleNames();
+ // 状态位编号 -> 中文名(下标即状态位序号)。
private static readonly string[] StateNames = BuildStateNames();
+ // 把角色值描述成中文名;未知编号退化为「角色N」,空值退化为「(无角色)」。
internal static string DescribeRole(object role)
{
if (role == null)
@@ -84,6 +126,7 @@ namespace pacs_win_uia.Interop
: "角色" + id;
}
+ // 把状态位掩码展开为逗号分隔的中文名列表。
internal static string DescribeState(object state)
{
if (state == null)
@@ -115,6 +158,7 @@ namespace pacs_win_uia.Interop
return string.Join(",", parts.ToArray());
}
+ // 把 COM VARIANT 里的数值安全转成 int;不支持的类型返回 fallback。
internal static int ToInt(object value, int fallback)
{
if (value is int)
@@ -135,6 +179,7 @@ namespace pacs_win_uia.Interop
return fallback;
}
+ // 构造角色名称表:下标=ROLE_SYSTEM_* 值,值=中文名;未设置的下标为 null。
private static string[] BuildRoleNames()
{
var names = new string[0x41];
@@ -205,6 +250,7 @@ namespace pacs_win_uia.Interop
return names;
}
+ // 构造状态名称表:下标=状态位序号,值=中文名。
private static string[] BuildStateNames()
{
var names = new string[31];
diff --git a/src/pacs_win_uia/Interop/NativeMethods.cs b/src/pacs_win_uia/Interop/NativeMethods.cs
index 70216ec..512c798 100644
--- a/src/pacs_win_uia/Interop/NativeMethods.cs
+++ b/src/pacs_win_uia/Interop/NativeMethods.cs
@@ -3,189 +3,288 @@ using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
+// =============================================================================
+// NativeMethods.cs —— Win32 P/Invoke 声明与常量(本工具原生调用的集中地)
+//
+// 职责:
+// 集中声明 user32/gdi32/kernel32/dwmapi 等 Win32 API、相关常量与互操作结构体。
+//
+// 用途:
+// 窗口枚举/样式读写、截图(PrintWindow/BitBlt)、低层鼠标/键盘钩子、分层窗口绘制
+// (UpdateLayeredWindow)、控制台准备(供 AppLog 使用)等。
+//
+// 注意事项:
+// - P/Invoke 声明必须与系统原型一致(参数类型/调用约定/CharSet),否则会崩溃或取到错值。
+// - 32/64 位差异:GetWindowLongPtr/SetWindowLongPtr 在 32 位系统上不存在,需按 IntPtr.Size
+// 分派到 GetWindowLong/SetWindowLong(见 GetWindowStyle/SetWindowStyle)。
+// - 结构体布局需与 Win32 一致(Sequential,注意包对齐)。
+// - 句柄(HANDLE/HWND/HDC)用 IntPtr,勿误用 int。
+// - 注意 UIA 是跨进程的:32 位与 64 位进程位宽不同时,某些原生/自动化互操作会失败。
+//
+// 要改什么就改哪里:
+// 新增原生调用 -> 在对应分区新增 [DllImport] 与常量(保持分区注释)。
+// 窗口样式读写 -> GetWindowStyle / SetWindowStyle。
+// =============================================================================
namespace pacs_win_uia.Interop
{
+ // 原生 Win32 声明的静态集中类。
internal static class NativeMethods
{
+ // 取窗口扩展样式(GWL_EXSTYLE)的索引。
internal const int GWL_EXSTYLE = -20;
+ // 扩展样式:点击穿透(透明区域不接收鼠标)。
internal const int WS_EX_TRANSPARENT = 0x00000020;
+ // 扩展样式:工具窗口(不出现在任务栏)。
internal const int WS_EX_TOOLWINDOW = 0x00000080;
+ // 扩展样式:点击不激活窗口。
internal const int WS_EX_NOACTIVATE = 0x08000000;
+ // 扩展样式:分层窗口(支持整体透明度/异形)。
internal const int WS_EX_LAYERED = 0x00080000;
+ // ShowWindow:隐藏。
internal const int SW_HIDE = 0;
+ // ShowWindow:显示但不激活。
internal const int SW_SHOWNOACTIVATE = 4;
+ // 消息:命中测试。
internal const int WM_NCHITTEST = 0x0084;
+ // 消息:鼠标激活窗口。
internal const int WM_MOUSEACTIVATE = 0x0021;
+ // 命中测试返回:客户区。
internal const int HTCLIENT = 1;
+ // 命中测试返回:透明(交给下层窗口)。
internal const int HTTRANSPARENT = -1;
+ // 鼠标激活返回:不激活。
internal const int MA_NOACTIVATE = 3;
+ // 虚拟键:Esc。
internal const int VK_ESCAPE = 0x1B;
+ // 虚拟键:鼠标左键。
internal const int VK_LBUTTON = 0x01;
+ // GetAncestor 标志:父窗口。
internal const uint GA_PARENT = 1;
+ // GetAncestor 标志:根窗口。
internal const uint GA_ROOT = 2;
+ // GetAncestor 标志:根属主窗口。
internal const uint GA_ROOTOWNER = 3;
+ // SendMessageTimeout 标志:目标无响应则中止。
internal const uint SMTO_ABORTIFHUNG = 0x0002;
+ // SendMessageTimeout 标志:阻塞等待。
internal const uint SMTO_BLOCK = 0x0001;
+ // AttachConsole 参数:附着到父进程控制台。
internal const int ATTACH_PARENT_PROCESS = -1;
+ // 控制台控制事件:关闭事件。
internal const uint CTRL_CLOSE_EVENT = 2;
+ // EnumWindows/EnumChildWindows 的回调委托。
internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
+ // 标准输出句柄编号。
internal const int STD_OUTPUT_HANDLE = -11;
+ // GetFileType:未知类型(无效句柄)。
internal const uint FILE_TYPE_UNKNOWN = 0;
+ // SetConsoleCtrlHandler 的回调委托。
internal delegate bool ConsoleCtrlHandler(uint controlType);
+ // 取标准设备句柄(如标准输出)。
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetStdHandle(int standardHandle);
+ // 取句柄类型(用于判断标准输出是否可用)。
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern uint GetFileType(IntPtr fileHandle);
+ // 为本进程分配一个控制台窗口。
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool AllocConsole();
+ // 附着到指定进程的控制台(-1 表示父进程)。
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool AttachConsole(int processId);
+ // 取本进程控制台窗口句柄(无则为 IntPtr.Zero)。
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetConsoleWindow();
+ // 注册/注销控制台控制事件处理回调。
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandler handler, bool add);
+ // 取当前前台窗口句柄。
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr GetForegroundWindow();
+ // 消息:热键。
internal const int WM_HOTKEY = 0x0312;
+ // 注册全局热键。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
+ // 注销全局热键。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool UnregisterHotKey(IntPtr hWnd, int id);
// ---------------------------------------------------------------- screenshots (segment 2)
+ // PrintWindow 标志:仅客户区。
internal const uint PW_CLIENTONLY = 1;
+ // PrintWindow 标志:渲染完整内容(含合成/加速内容)。
internal const uint PW_RENDERFULLCONTENT = 2;
+ // BitBlt 光栅操作码:直接复制源。
internal const uint SRCCOPY = 0x00CC0020;
+ // ShowWindow:最小化。
internal const int SW_MINIMIZE = 6;
+ // 把窗口内容画到指定 DC(可截取非前台/被遮挡窗口)。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, uint nFlags);
+ // 取窗口 DC。
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr GetWindowDC(IntPtr hWnd);
+ // 释放 DC。
[DllImport("user32.dll", SetLastError = true)]
internal static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
+ // 创建兼容 DC。
[DllImport("gdi32.dll", SetLastError = true)]
internal static extern IntPtr CreateCompatibleDC(IntPtr hdc);
+ // 创建兼容位图。
[DllImport("gdi32.dll", SetLastError = true)]
internal static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int width, int height);
+ // 选择 GDI 对象到 DC,返回旧对象。
[DllImport("gdi32.dll", SetLastError = true)]
internal static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject);
+ // 位块传送(复制像素)。
[DllImport("gdi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool BitBlt(
IntPtr hdcDest, int xDest, int yDest, int width, int height,
IntPtr hdcSrc, int xSrc, int ySrc, uint rop);
+ // 删除 GDI 对象(位图等)。
[DllImport("gdi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
+ // 删除 DC。
[DllImport("gdi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteDC(IntPtr hdc);
+ // 枚举顶层窗口。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
+ // 枚举子窗口。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
+ // 取屏幕点命中的窗口。
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr WindowFromPoint(Point point);
+ // 取父窗口内命中的子窗口(可按标志跳过不可见/禁用/透明)。
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr ChildWindowFromPointEx(IntPtr parent, Point point, uint flags);
+ // 取祖先窗口(父/根/根属主)。
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr GetAncestor(IntPtr hWnd, uint gaFlags);
+ // 取窗口标题文本。
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
+ // 取窗口标题长度。
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int GetWindowTextLength(IntPtr hWnd);
+ // 取窗口类名。
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
+ // 取创建窗口的线程/进程 ID。
[DllImport("user32.dll", SetLastError = true)]
internal static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
+ // 窗口句柄是否有效。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsWindow(IntPtr hWnd);
+ // 窗口是否可见。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsWindowVisible(IntPtr hWnd);
+ // 窗口是否最小化。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsIconic(IntPtr hWnd);
+ // 取窗口屏幕矩形(含边框)。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
+ // 创建矩形区域。
[DllImport("gdi32.dll", SetLastError = true)]
internal static extern IntPtr CreateRectRgn(int left, int top, int right, int bottom);
+ // 取窗口区域(判断异形窗口可见范围)。
[DllImport("user32.dll", SetLastError = true)]
internal static extern int GetWindowRgn(IntPtr hWnd, IntPtr region);
+ // 取窗口矩形(DWM 版本,含扩展边框)。
[DllImport("dwmapi.dll", EntryPoint = "DwmGetWindowAttribute")]
internal static extern int DwmGetWindowRectangle(IntPtr hwnd, int attribute, out RECT value, int size);
+ // 取客户区矩形。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetClientRect(IntPtr hWnd, out RECT rect);
+ // 客户区坐标转屏幕坐标。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
+ // 取光标屏幕坐标。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(out POINT point);
+ // 消息:取控件文本(WM_GETTEXT)。
internal const int WM_GETTEXT = 0x000D;
+ // DWM 属性:窗口是否被 DWM 隐形(cloaked)。
internal const int DWMWA_CLOAKED = 14;
+ // ChildWindowFromPointEx 标志:不跳过任何类型。
internal const uint CWP_ALL = 0x0000;
+ // ChildWindowFromPointEx 标志:跳过不可见窗口。
internal const uint CWP_SKIPINVISIBLE = 0x0001;
+ // ChildWindowFromPointEx 标志:跳过禁用窗口。
internal const uint CWP_SKIPDISABLED = 0x0002;
+ // ChildWindowFromPointEx 标志:跳过透明窗口。
internal const uint CWP_SKIPTRANSPARENT = 0x0004;
+ // 样式:窗口可见。
internal const int WS_VISIBLE = 0x10000000;
+ // 取异步按键状态(高位按下)。
[DllImport("user32.dll", SetLastError = true)]
internal static extern short GetAsyncKeyState(int virtualKey);
+ // 发送消息(同步,可能阻塞)。
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern IntPtr SendMessage(
IntPtr hWnd,
@@ -196,72 +295,112 @@ namespace pacs_win_uia.Interop
// ---------------------------------------------------------------- low-level mouse hook
// Used by the picker to keep the confirmation click from reaching the target application.
+ // 钩子类型:低层鼠标钩子。
internal const int WH_MOUSE_LL = 14;
+ // 鼠标消息:左键按下。
internal const int WM_LBUTTONDOWN = 0x0201;
+ // 鼠标消息:左键抬起。
internal const int WM_LBUTTONUP = 0x0202;
+ // 鼠标消息:右键按下。
internal const int WM_RBUTTONDOWN = 0x0204;
+ // 鼠标消息:右键抬起。
internal const int WM_RBUTTONUP = 0x0205;
+ // 鼠标消息:移动。
internal const int WM_MOUSEMOVE = 0x0200;
+ // 鼠标消息:中键按下。
internal const int WM_MBUTTONDOWN = 0x0207;
+ // 鼠标消息:中键抬起。
internal const int WM_MBUTTONUP = 0x0208;
+ // 鼠标消息:滚轮。
internal const int WM_MOUSEWHEEL = 0x020A;
+ // 鼠标消息:侧键1按下。
internal const int WM_XBUTTONDOWN = 0x020B;
+ // 鼠标消息:侧键抬起。
internal const int WM_XBUTTONUP = 0x020C;
+ // 鼠标消息:横向滚轮。
internal const int WM_MOUSEHWHEEL = 0x020E;
+ // 钩子类型:低层键盘钩子。
internal const int WH_KEYBOARD_LL = 13;
+ // 键盘消息:按键按下。
internal const int WM_KEYDOWN = 0x0100;
+ // 键盘消息:按键抬起。
internal const int WM_KEYUP = 0x0101;
+ // 键盘消息:系统键按下(如 Alt 组合)。
internal const int WM_SYSKEYDOWN = 0x0104;
+ // 键盘消息:系统键抬起。
internal const int WM_SYSKEYUP = 0x0105;
+ // 低层键盘钩子回调委托。
internal delegate IntPtr LowLevelKeyboardProc(int code, IntPtr wParam, IntPtr lParam);
+ // 低层键盘钩子事件数据(KBDLLHOOKSTRUCT)。
[StructLayout(LayoutKind.Sequential)]
internal struct KBDLLHOOKSTRUCT
{
+ // 虚拟键码。
public uint VirtualKey;
+ // 硬件扫描码。
public uint ScanCode;
+ // 标志位。
public uint Flags;
+ // 消息时间戳。
public uint Time;
+ // 附加上下文。
public IntPtr ExtraInfo;
}
+ // 安装键盘钩子(低层键盘用此重载)。
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr SetWindowsHookEx(int hookId, LowLevelKeyboardProc callback, IntPtr module, uint threadId);
+ // 低层鼠标钩子回调委托。
internal delegate IntPtr LowLevelMouseProc(int code, IntPtr wParam, IntPtr lParam);
+ // 低层鼠标钩子事件数据(MSLLHOOKSTRUCT)。
[StructLayout(LayoutKind.Sequential)]
internal struct MSLLHOOKSTRUCT
{
+ // 屏幕坐标。
public POINT Point;
+ // 滚轮/侧键数据。
public uint MouseData;
+ // 标志位。
public uint Flags;
+ // 消息时间戳。
public uint Time;
+ // 附加上下文。
public IntPtr ExtraInfo;
}
+ // 安装鼠标钩子(低层鼠标用此重载)。
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr SetWindowsHookEx(int hookId, LowLevelMouseProc callback, IntPtr module, uint threadId);
+ // 卸载钩子。
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool UnhookWindowsHookEx(IntPtr hook);
+ // 把事件传给钩子链的下一环。
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr CallNextHookEx(IntPtr hook, int code, IntPtr wParam, IntPtr lParam);
+ // 取模块句柄(低层钩子传 module 用)。
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern IntPtr GetModuleHandle(string moduleName);
// ---------------------------------------------------------------- layered window painting
// The floating bar draws itself so its background and buttons can have separate transparency.
+ // 尺寸结构(SIZE):宽高。
[StructLayout(LayoutKind.Sequential)]
internal struct SIZE
{
+ // 宽。
public int Width;
+ // 高。
public int Height;
+ // 构造尺寸。
public SIZE(int width, int height)
{
Width = width;
@@ -269,15 +408,21 @@ namespace pacs_win_uia.Interop
}
}
+ // 混合结构(BLENDFUNCTION):分层窗口的 alpha 混合参数;Pack=1 与 Win32 布局一致。
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct BLENDFUNCTION
{
+ // 混合操作(通常 AC_SRC_OVER=0)。
public byte BlendOp;
+ // 混合标志(通常 0)。
public byte BlendFlags;
+ // 源位图整体不透明度(0-255)。
public byte SourceConstantAlpha;
+ // alpha 格式(AC_SRC_ALPHA=1 表示按像素 alpha)。
public byte AlphaFormat;
}
+ // 分层窗口绘制:整幅位图连同 alpha 一次性更新。
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool UpdateLayeredWindow(
IntPtr hWnd,
@@ -290,9 +435,11 @@ namespace pacs_win_uia.Interop
ref BLENDFUNCTION pblend,
int dwFlags);
+ // 取窗口 DC(用后需 ReleaseDC)。
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr GetDC(IntPtr hWnd);
+ // 发消息并带超时(避免目标无响应时卡死)。
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern IntPtr SendMessageTimeout(
IntPtr hWnd,
@@ -303,17 +450,22 @@ namespace pacs_win_uia.Interop
uint timeout,
out IntPtr result);
+ // 一次取窗口样式/矩形等信息(见 WINDOWINFO)。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetWindowInfo(IntPtr hWnd, ref WINDOWINFO windowInfo);
+ // 屏幕坐标转客户区坐标。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ScreenToClient(IntPtr hWnd, ref POINT point);
+ // 取窗口 DWM 属性(如是否 cloaked)。
[DllImport("dwmapi.dll")]
internal static extern int DwmGetWindowAttribute(IntPtr hwnd, int attribute, out int value, int size);
+ // GetWindowInfo 返回的窗口信息:一次替代 GetWindowRect+GetClientRect+ClientToScreen+样式读取。
+ // 两个矩形都用屏幕坐标。
///
/// One-call replacement for GetWindowRect + GetClientRect + ClientToScreen + style reads.
/// Both rectangles are in screen coordinates.
@@ -321,40 +473,55 @@ namespace pacs_win_uia.Interop
[StructLayout(LayoutKind.Sequential)]
internal struct WINDOWINFO
{
+ // 结构大小(调用前须填 Marshal.SizeOf)。
internal int cbSize;
+ // 窗口矩形(屏幕坐标)。
internal RECT rcWindow;
+ // 客户区矩形(屏幕坐标)。
internal RECT rcClient;
+ // 窗口样式。
internal int dwStyle;
+ // 窗口扩展样式。
internal int dwExStyle;
+ // 窗口状态。
internal int dwWindowStatus;
+ // 窗口边框宽度。
internal uint cxWindowBorders;
+ // 窗口边框高度。
internal uint cyWindowBorders;
+ // 窗口类型原子。
internal ushort atomWindowType;
+ // 创建者版本。
internal ushort wCreatorVersion;
}
+ // 64 位下取窗口长整型样式(GWL_*)。
[DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetWindowLongPtr64(
IntPtr hWnd,
int nIndex);
+ // 32 位下取窗口长整型样式(32 位系统无 ...Ptr 版本)。
[DllImport("user32.dll", EntryPoint = "GetWindowLong", SetLastError = true)]
private static extern int GetWindowLong32(
IntPtr hWnd,
int nIndex);
+ // 64 位下设置窗口长整型样式(GWL_*)。
[DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr SetWindowLongPtr64(
IntPtr hWnd,
int nIndex,
IntPtr dwNewLong);
+ // 32 位下设置窗口长整型样式。
[DllImport("user32.dll", EntryPoint = "SetWindowLong", SetLastError = true)]
private static extern int SetWindowLong32(
IntPtr hWnd,
int nIndex,
int dwNewLong);
+ // 设置窗口位置/大小/层级。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetWindowPos(
@@ -366,14 +533,17 @@ namespace pacs_win_uia.Interop
int cy,
uint uFlags);
+ // 显示/隐藏/最小化等。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
+ // 把窗口设为前台。
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetForegroundWindow(IntPtr hWnd);
+ // 读取窗口扩展样式(GWL_EXSTYLE),按位宽分派 32/64 位实现。
internal static int GetWindowStyle(IntPtr hWnd)
{
if (IntPtr.Size == 8)
@@ -384,6 +554,7 @@ namespace pacs_win_uia.Interop
return GetWindowLong32(hWnd, GWL_EXSTYLE);
}
+ // 设置窗口扩展样式(GWL_EXSTYLE),按位宽分派 32/64 位实现。
internal static IntPtr SetWindowStyle(IntPtr hWnd, int style)
{
if (IntPtr.Size == 8)
@@ -394,32 +565,43 @@ namespace pacs_win_uia.Interop
return new IntPtr(SetWindowLong32(hWnd, GWL_EXSTYLE, style));
}
+ // 矩形结构(RECT):屏幕/客户区坐标。
[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
+ // 左。
internal int Left;
+ // 上。
internal int Top;
+ // 右。
internal int Right;
+ // 下。
internal int Bottom;
+ // 转成 System.Drawing.Rectangle。
internal Rectangle ToRectangle()
{
return Rectangle.FromLTRB(Left, Top, Right, Bottom);
}
}
+ // 点结构(POINT)。
[StructLayout(LayoutKind.Sequential)]
internal struct POINT
{
+ // X 坐标。
internal int X;
+ // Y 坐标。
internal int Y;
+ // 构造点。
internal POINT(int x, int y)
{
X = x;
Y = y;
}
+ // 转成 System.Drawing.Point。
internal Point ToDrawingPoint()
{
return new Point(X, Y);
diff --git a/src/pacs_win_uia/Models/AppSettings.cs b/src/pacs_win_uia/Models/AppSettings.cs
index cf61e9b..7307d41 100644
--- a/src/pacs_win_uia/Models/AppSettings.cs
+++ b/src/pacs_win_uia/Models/AppSettings.cs
@@ -1,3 +1,34 @@
+// =============================================================================
+// AppSettings.cs —— 顶层配置模型(settings.json 的数据契约)
+//
+// 职责:
+// 定义本工具所有配置节及其默认值,并用 Normalize() 做「兼容性修复」。类上标注
+// [DataContract],通过 DataContractJsonSerializer 读写 JSON。
+//
+// 配置节一览(默认值见各自构造函数/常量):
+// Version 配置版本(当前 CurrentVersion=1,Normalize 时强制写入当前版本)。
+// Ui 界面:控件树深度/节点数/超时、刷新间隔、设置窗口位置等。
+// FloatingButton 悬浮条:显示条件、跟随刷新间隔、条与按钮定义。
+// Commands 命令钩子:启动/退出/定时/单次的命令组。
+// Ocr OCR 服务总开关与地址(默认关闭)。
+// Read 无界面读取:默认超时、是否跳过停用项。
+// Screenshot 截图:保存目录、是否允许恢复最小化窗口、恢复等待时间。
+//
+// Normalize 的兼容策略(关键):
+// 缺字段 = 用默认(对象为 null 时补 new、列表为空时补默认项)。
+// 0 = 当默认处理(Clamp 约定:value==0 返回 fallback;因为旧 JSON 缺字段会被反序列
+// 化成 0,无法与「真的设成 0」区分)。
+// 越界 = 夹取到 [minimum, maximum]。
+//
+// 刷新间隔 300ms 的含义:
+// DefaultRefreshIntervalMs=300 是控件树读取与悬浮条跟随的默认刷新周期,范围 50–60000ms
+// (MinimumRefreshIntervalMs / MaximumRefreshIntervalMs)。太快会加重 UIA 负担,太慢则
+// 界面跟不上前台窗口变化。
+//
+// 要改什么就改哪里:
+// 加/改配置项 -> 对应节类里加属性并标 [DataMember],再在 Normalize 里补默认与夹取。
+// 改默认值 -> 各节构造函数,或本文件顶部常量。
+// =============================================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -5,6 +36,7 @@ using System.Runtime.Serialization;
namespace pacs_win_uia.Models
{
+ // 顶层配置对象:settings.json 的根。
///
/// Application settings, stored as a plain JSON file next to the executable so it can be edited
/// by hand and shipped alongside the build (never embedded in the assembly).
@@ -12,16 +44,22 @@ namespace pacs_win_uia.Models
[DataContract]
public sealed class AppSettings
{
+ // 当前配置版本号;Normalize 时强制写回该值。
public const int CurrentVersion = 1;
+ // 刷新间隔默认值(毫秒):控件树读取与悬浮条跟随。
public const int DefaultRefreshIntervalMs = 300;
+ // 刷新间隔下限(毫秒)。
public const int MinimumRefreshIntervalMs = 50;
+ // 刷新间隔上限(毫秒)。
public const int MaximumRefreshIntervalMs = 60000;
+ // 把任意刷新间隔夹取到合法范围;0 视为默认值。
public static int NormalizeRefreshIntervalMs(int value)
{
return Clamp(value, MinimumRefreshIntervalMs, MaximumRefreshIntervalMs, DefaultRefreshIntervalMs);
}
+ // 构造时先把所有配置节置为非 null,避免手改/缺字段导致的空引用。
public AppSettings()
{
Ui = new UiSettings();
@@ -32,27 +70,35 @@ namespace pacs_win_uia.Models
Screenshot = new ScreenshotSettings();
}
+ // 配置版本号。
[DataMember(Order = 1)]
public int Version { get; set; }
+ // 界面相关设置。
[DataMember(Order = 2)]
public UiSettings Ui { get; set; }
+ // 悬浮条设置。
[DataMember(Order = 3)]
public FloatingButtonSettings FloatingButton { get; set; }
+ // 命令钩子设置。
[DataMember(Order = 4)]
public CommandSettings Commands { get; set; }
+ // OCR 设置。
[DataMember(Order = 5)]
public OcrSettings Ocr { get; set; }
+ // 无界面读取设置。
[DataMember(Order = 6)]
public ReadSettings Read { get; set; }
+ // 截图设置。
[DataMember(Order = 7)]
public ScreenshotSettings Screenshot { get; set; }
+ // 生成一份带默认值的配置(先构造再 Normalize)。
public static AppSettings CreateDefault()
{
var settings = new AppSettings { Version = CurrentVersion };
@@ -60,6 +106,7 @@ namespace pacs_win_uia.Models
return settings;
}
+ // 补全缺失的配置节并把数值夹取到合理范围;手改文件缺项或填了离谱数值都不能让工具崩溃。
///
/// Fills missing sections and clamps values into sane ranges. A hand-edited file with a
/// missing section or an absurd number must not break the tool.
@@ -157,6 +204,7 @@ namespace pacs_win_uia.Models
}
}
+ // 夹取工具:value==0 视为「未设置」返回 fallback;否则夹到 [minimum, maximum]。
private static int Clamp(int value, int minimum, int maximum, int fallback)
{
if (value == 0)
@@ -168,9 +216,11 @@ namespace pacs_win_uia.Models
}
}
+ // 界面设置:控件树读取参数、刷新间隔与设置窗口位置。
[DataContract]
public sealed class UiSettings
{
+ // 构造默认值。
public UiSettings()
{
AutoReadTreeOnSelect = true;
@@ -181,26 +231,32 @@ namespace pacs_win_uia.Models
TreeRefreshIntervalMs = AppSettings.DefaultRefreshIntervalMs;
}
+ // 选中窗口列表某行时是否自动读取控件树。
[DataMember(Order = 1)]
[Description("在窗口列表里选中一行时是否自动读取控件树。关掉后只能点「检查选中窗口」。")]
public bool AutoReadTreeOnSelect { get; set; }
+ // 是否用底色标出当前前台窗口。
[DataMember(Order = 2)]
[Description("窗口列表里是否用底色标出当前前台窗口(屏幕上最上方的那个)。")]
public bool HighlightForegroundWindow { get; set; }
+ // 控件树最大深度。
[DataMember(Order = 3)]
[Description("控件树最大深度。")]
public int TreeMaxDepth { get; set; }
+ // 控件树最大节点数(超出会截断并标记不完整)。
[DataMember(Order = 4)]
[Description("控件树最大节点数,超出会被截断并标记为不完整。")]
public int TreeMaxNodes { get; set; }
+ // 控件树读取超时(秒)。
[DataMember(Order = 5)]
[Description("控件树读取超时(秒)。")]
public int TreeTimeoutSeconds { get; set; }
+ // 设置窗口上次位置/大小(0=未记录;记下的位置若已不在任何屏幕则忽略,可能显示器没了)。
///
/// Where the settings dialog was last placed. Remembered so it opens where the operator left it;
/// all values are 0 until it has been moved once, and a remembered position that is no longer on
@@ -210,19 +266,24 @@ namespace pacs_win_uia.Models
[Description("设置窗口上次的位置与大小(0 = 还没有记录,首次打开会居中)。")]
public int SettingsWindowX { get; set; }
+ // 设置窗口上次的 Y 坐标。
[DataMember(Order = 7, EmitDefaultValue = false)]
public int SettingsWindowY { get; set; }
+ // 设置窗口上次的宽度。
[DataMember(Order = 8, EmitDefaultValue = false)]
public int SettingsWindowWidth { get; set; }
+ // 设置窗口上次的高度。
[DataMember(Order = 9, EmitDefaultValue = false)]
public int SettingsWindowHeight { get; set; }
+ // 控件树及高亮重解析的刷新间隔(毫秒)。
[DataMember(Order = 10)]
[Description("控件树及高亮重解析刷新间隔(毫秒,50-60000,默认300;0按默认值处理)。")]
public int TreeRefreshIntervalMs { get; set; }
+ // 是否记录过有效的设置窗口大小(不全为 0);仅运行时使用,不序列化。
[IgnoreDataMember]
public bool HasSettingsWindowBounds
{
@@ -230,15 +291,18 @@ namespace pacs_win_uia.Models
}
}
+ // 悬浮条设置:条定义列表与跟随/显示的刷新间隔。
[DataContract]
public sealed class FloatingButtonSettings
{
+ // 构造默认值。
public FloatingButtonSettings()
{
RefreshIntervalMs = AppSettings.DefaultRefreshIntervalMs;
Bars = new List();
}
+ // 悬浮条列表;每条在其页面/窗口条件成立时显示,位置相对该窗口。
///
/// Floating bars. Each one shows only while its page/window condition holds, and sits at a
/// position relative to that window.
@@ -246,10 +310,12 @@ namespace pacs_win_uia.Models
[DataMember(Order = 1)]
public List Bars { get; set; }
+ // 悬浮条跟随、显示条件及导入 path 的刷新间隔(毫秒)。
[DataMember(Order = 2)]
[Description("悬浮条跟随、显示条件及导入 path 的刷新间隔(毫秒,50-60000,默认300;0按默认值处理)。")]
public int RefreshIntervalMs { get; set; }
+ // 生成一条可直接使用的示例悬浮条(默认停用),便于发现该功能。
/// One ready-to-use bar so the feature is discoverable.
public static List CreateDefaultBars()
{
@@ -279,24 +345,30 @@ namespace pacs_win_uia.Models
}
}
+ // 命令组的执行时机。
/// When a group of commands runs.
[DataContract]
public enum CommandTriggerKind
{
+ // 启动时一次。
[EnumMember]
Start,
+ // 退出时一次。
[EnumMember]
Exit,
+ // 工具运行期间按间隔反复执行(定时 on)。
/// Runs repeatedly on an interval while the tool is open.
[EnumMember]
Interval,
+ // 仅启动时执行一次(单次 once)。
[EnumMember]
Once
}
+ // 一组带同一执行时机的命名命令;同一种时机可以有多个组(设置界面「新增执行时机」)。
///
/// A named group of commands with one execution moment. Several groups may share a moment, which
/// is what the "新增执行时机" button in the settings dialog creates.
@@ -304,6 +376,7 @@ namespace pacs_win_uia.Models
[DataContract]
public sealed class CommandTrigger
{
+ // 构造默认值:单次时机、间隔 60 秒、启用。
public CommandTrigger()
{
Kind = CommandTriggerKind.Once;
@@ -312,30 +385,37 @@ namespace pacs_win_uia.Models
Commands = new List();
}
+ // 组名,仅用于界面显示。
[DataMember(Order = 1)]
[Description("这组命令的名字,只用于界面显示。")]
public string Name { get; set; }
+ // 执行时机。
[DataMember(Order = 2)]
[Description("执行时机:启动 / 退出 / 定时(on) / 单次(once)。")]
public CommandTriggerKind Kind { get; set; }
+ // 定时(on)时机的间隔秒数。
[DataMember(Order = 3)]
[Description("定时(on)时机的间隔秒数。")]
public int IntervalSeconds { get; set; }
+ // 整组是否启用(停用的时机不执行任何命令)。
[DataMember(Order = 4)]
[Description("整组是否启用。停用的时机不会执行任何命令。")]
public bool Enabled { get; set; }
+ // 该组包含的命令。
[DataMember(Order = 5)]
public List Commands { get; set; }
+ // 界面显示用:组名 + 时机文字。
public override string ToString()
{
return (string.IsNullOrEmpty(Name) ? "(未命名)" : Name) + " —— " + DescribeKind(Kind);
}
+ // 把执行时机枚举翻译成界面中文。
public static string DescribeKind(CommandTriggerKind kind)
{
switch (kind)
@@ -352,18 +432,22 @@ namespace pacs_win_uia.Models
}
}
+ // 命令设置根:包含所有命令组(执行时机)。
[DataContract]
public sealed class CommandSettings
{
+ // 构造默认空列表。
public CommandSettings()
{
Triggers = new List();
}
+ // 命令组列表(同一种时机可以有多个组)。
/// Execution moments; the user can add more than one group per moment.
[DataMember(Order = 1)]
public List Triggers { get; set; }
+ // 生成默认的四个命令组:启动 / 退出 / 定时 / 单次。
public static List CreateDefaultTriggers()
{
return new List
@@ -376,9 +460,11 @@ namespace pacs_win_uia.Models
}
}
+ // 单条命令定义。
[DataContract]
public sealed class CommandDefinition
{
+ // 构造默认值:间隔 60 秒、启用、超时 30 秒。
public CommandDefinition()
{
IntervalSeconds = 60;
@@ -386,35 +472,43 @@ namespace pacs_win_uia.Models
TimeoutSeconds = 30;
}
+ // 命令名(可空,界面显示用)。
[DataMember(Order = 1)]
public string Name { get; set; }
+ // 命令行(经 cmd.exe /c 执行)。
[DataMember(Order = 2)]
[Description("命令行,通过 cmd.exe /c 执行(可以写一行式命令与管道)。")]
public string CommandLine { get; set; }
+ // 工作目录(留空=exe 所在目录)。
[DataMember(Order = 3)]
[Description("工作目录,留空表示 exe 所在目录。")]
public string WorkingDirectory { get; set; }
+ // 持续(on)命令的间隔秒数。
[DataMember(Order = 4)]
[Description("持续(on)命令的间隔秒数。")]
public int IntervalSeconds { get; set; }
+ // 单次命令执行超时(秒),超时会结束该进程。
[DataMember(Order = 5)]
[Description("单次命令的执行超时(秒),超时会结束该进程。")]
public int TimeoutSeconds { get; set; }
+ // 是否启用(停用则不执行)。
[DataMember(Order = 6)]
[Description("是否启用。停用的命令不会被执行。")]
public bool Enabled { get; set; }
+ // 界面显示用:有名字用名字,否则用命令行。
public override string ToString()
{
return string.IsNullOrEmpty(Name) ? CommandLine : Name;
}
}
+ // OCR 设置:默认关闭总开关,只有开启后才发往配置的本地 ocr-server 地址。
///
/// OCR runs against a local ocr-server (FastAPI + PaddleOCR). The master switch defaults to off:
/// nothing is sent anywhere until the operator turns it on, and only to the configured address.
@@ -422,6 +516,7 @@ namespace pacs_win_uia.Models
[DataContract]
public sealed class OcrSettings
{
+ // 构造默认值(地址与语言),并调用 ApplyDefaults 兜底。
public OcrSettings()
{
Language = "zh-CN";
@@ -430,34 +525,42 @@ namespace pacs_win_uia.Models
ApplyDefaults();
}
+ // OCR 总开关(默认关;关闭时不调用任何 OCR 服务)。
[DataMember(Order = 1)]
[Description("OCR 总开关。关闭时本工具**完全不会**调用任何 OCR 服务(段二实现)。")]
public bool Enabled { get; set; }
+ // OCR 服务地址。
[DataMember(Order = 2)]
[Description("OCR 服务地址(默认本机 ocr-server)。识别内容只发到这个地址,不上传外部服务。")]
public string BaseUrl { get; set; }
+ // 识别语言(仅记录,实际由服务端模型决定)。
[DataMember(Order = 3)]
[Description("识别语言(服务端模型决定,仅记录用途)。")]
public string Language { get; set; }
+ // 识别时是否保存截图(可能含患者信息,慎用)。
[DataMember(Order = 4)]
[Description("识别时是否保存截图。保存的图片可能包含患者信息,请自行控制目录与保留期限。")]
public bool SaveScreenshots { get; set; }
+ // 截图保存目录(空=exe 目录下的 screenshots)。
[DataMember(Order = 5)]
[Description("截图保存目录。留空表示 exe 目录下的 screenshots。")]
public string ScreenshotDirectory { get; set; }
+ // 识别结果最小置信度(0-1)。
[DataMember(Order = 6)]
[Description("识别结果的最小置信度(0-1),低于该值的文本会被服务端过滤。")]
public double MinConfidence { get; set; }
+ // 单次识别总超时(秒,含排队)。
[DataMember(Order = 7)]
[Description("单次识别的总超时(秒),包含排队等待。")]
public int TimeoutSeconds { get; set; }
+ // 对空地址/语言/非法超时与置信度做兜底(0 或越界时回默认)。
public void ApplyDefaults()
{
if (string.IsNullOrWhiteSpace(BaseUrl))
@@ -482,41 +585,50 @@ namespace pacs_win_uia.Models
}
}
+ // 截图设置:默认不恢复最小化窗口(可见、会闪一下,需显式开启)。
/// Screenshot behaviour. Restoring a minimized window is opt-in because it is visible.
[DataContract]
public sealed class ScreenshotSettings
{
+ // 构造默认值:恢复等待 350ms。
public ScreenshotSettings()
{
RestoreSettleMs = 350;
}
+ // 截图保存目录(空=exe 目录下的 screenshots)。
[DataMember(Order = 1)]
[Description("截图保存目录,留空表示 exe 目录下的 screenshots。")]
public string Directory { get; set; }
+ // 是否允许为截图临时恢复最小化窗口(默认关)。
[DataMember(Order = 2)]
[Description("是否允许为截图临时恢复最小化窗口。开启后窗口会闪一下、可能改变前台窗口,默认关闭。")]
public bool AllowRestoreMinimized { get; set; }
+ // 恢复最小化窗口后等待界面绘制的时间(毫秒)。
[DataMember(Order = 3)]
[Description("临时恢复最小化窗口后等待界面绘制的时间(毫秒)。")]
public int RestoreSettleMs { get; set; }
}
+ // 无界面读取设置。
[DataContract]
public sealed class ReadSettings
{
+ // 构造默认值:默认超时 10 秒、跳过停用条目。
public ReadSettings()
{
DefaultTimeoutSeconds = 10;
SkipDisabled = true;
}
+ // 等待目标窗口出现的默认超时(秒)。
[DataMember(Order = 1)]
[Description("无界面读取时等待目标窗口出现的默认超时(秒)。单条监控可以覆盖它。")]
public int DefaultTimeoutSeconds { get; set; }
+ // 是否跳过已停用的监控条目。
[DataMember(Order = 2)]
[Description("无界面读取时是否跳过已停用的监控条目。")]
public bool SkipDisabled { get; set; }
diff --git a/src/pacs_win_uia/Models/ControlLocator.cs b/src/pacs_win_uia/Models/ControlLocator.cs
index ac07c96..fd36f6e 100644
--- a/src/pacs_win_uia/Models/ControlLocator.cs
+++ b/src/pacs_win_uia/Models/ControlLocator.cs
@@ -5,20 +5,43 @@ using System.Text;
namespace pacs_win_uia.Models
{
+ // ============================================================================
+ // ControlLocator —— 监控定义里“保存下来的定位信息”所用的模型与兼容外壳。
+ //
+ // 职责:
+ // - ControlSourcePreference:重新定位时用哪个无障碍来源(Auto / Uia / Msaa / Win32);
+ // - ControlLocatorSegment、Win32LocatorSegment、ControlLocatorFormat:旧结构化路径的“只读历史”,
+ // 仅为反序列化与显示保留,绝不执行;
+ // - ControlValueKeys:各来源可读取的属性键目录(含跨来源的选中 / 焦点 / OCR 键)。
+ //
+ // 被谁调用:ControlMonitorDefinition(保存 / 读取字段)、监控编辑界面、取值读取与导出。
+ //
+ // 要改什么就改哪里:
+ // - 来源枚举:ControlSourcePreference;
+ // - 可取值键:ControlValueKeys.Uia / Msaa / Win32 与 For / ForSource;
+ // - 旧路径显示:ControlLocatorFormat。
+ //
+ // 注意:本文件里的旧段类型(ControlLocatorSegment / Win32LocatorSegment)只用于兼容旧文件;
+ // 真正的定位一律走 ControlMonitorDefinition.ControlPath(XPath)。
+ // ============================================================================
/// Which source a saved control should be re-resolved with.
[DataContract]
public enum ControlSourcePreference
{
+ // Auto:求值前先选一个可用来源,只求值一次。
/// Choose an available snapshot before evaluating XPath once.
[EnumMember]
Auto,
+ // Uia:强制使用 UIA 快照。
[EnumMember]
Uia,
+ // Msaa:强制使用 MSAA 快照。
[EnumMember]
Msaa,
+ // Win32:强制使用 Win32 快照。
[EnumMember]
Win32
}
@@ -27,22 +50,28 @@ namespace pacs_win_uia.Models
[DataContract]
public sealed class ControlLocatorSegment
{
+ // ControlType:旧字段——控件类型名(如 ControlType.Button)。
[DataMember(Order = 1, EmitDefaultValue = false)]
public string ControlType { get; set; }
+ // Name:旧字段——控件名称。
[DataMember(Order = 2, EmitDefaultValue = false)]
public string Name { get; set; }
+ // AutomationId:旧字段——控件 AutomationId。
[DataMember(Order = 3, EmitDefaultValue = false)]
public string AutomationId { get; set; }
+ // ClassName:旧字段——控件类名。
[DataMember(Order = 5, EmitDefaultValue = false)]
public string ClassName { get; set; }
+ // Index:旧字段——同一类型兄弟中的 0 基序号;-1 表示未指定。
/// ZERO-based ordinal among ALL same-type siblings; -1 means unspecified.
[DataMember(Order = 4)]
public int Index { get; set; }
+ // ToString:旧格式显示文本(类型[AutomationId] / 类型:名称 / 类型#序号)。
public override string ToString()
{
string type = string.IsNullOrEmpty(ControlType) ? "?" : ControlType.Replace("ControlType.", string.Empty);
@@ -59,21 +88,26 @@ namespace pacs_win_uia.Models
[DataContract]
public sealed class Win32LocatorSegment
{
+ // ClassName:旧字段——窗口类名。
[DataMember(Order = 1, EmitDefaultValue = false)]
public string ClassName { get; set; }
+ // Index:旧字段——同类兄弟中的序号。
[DataMember(Order = 2)]
public int Index { get; set; }
+ // ToString:旧格式显示(类名#序号)。
public override string ToString()
{
return (string.IsNullOrEmpty(ClassName) ? "(无类名)" : ClassName) + "#" + Index;
}
}
+ // ControlLocatorFormat:旧路径的显示辅助,只生成给人看的字符串,绝不能被当定位器执行。
/// Legacy display helpers only. These strings must never be executed as locators.
public static class ControlLocatorFormat
{
+ // DescribeUiaPath:把旧 UIA 段列表拼成 “A > B > C” 的显示文本;空则返回空串。
public static string DescribeUiaPath(IList segments)
{
if (segments == null || segments.Count == 0)
@@ -95,6 +129,7 @@ namespace pacs_win_uia.Models
return builder.ToString();
}
+ // DescribeWin32Path:把旧 Win32 段列表拼成 “A > B > C” 的显示文本;空则返回空串。
public static string DescribeWin32Path(IList segments)
{
if (segments == null || segments.Count == 0)
@@ -117,21 +152,26 @@ namespace pacs_win_uia.Models
}
}
+ // ControlValueKeys:已定位控件可按来源读取的属性键目录(外加跨来源键)。
/// Keys that can be read from a resolved control, per source.
public static class ControlValueKeys
{
+ // Selected:跨来源键——该控件当前是否处于选中状态。
/// Cross-source key: is this control the selected one.
public const string Selected = "选中状态";
+ // Focused:跨来源键——该控件当前是否拥有键盘焦点。
/// Cross-source key: does this control currently have keyboard focus.
public const string Focused = "焦点状态";
+ // OcrText:跨来源键——对控件截图并送本地 OCR 得到的文本;需开启 OCR,结果标记为 OCR 来源。
///
/// Cross-source key: read the text by screenshotting this control and sending it to the local
/// OCR service. Only usable when OCR is switched on; the result is marked as OCR-derived.
///
public const string OcrText = "OCR文本";
+ // Uia:UIA 来源可读取的属性键列表。
public static readonly IList Uia = new List
{
"Name", "AutomationId", "ControlType", "ClassName", "FrameworkId",
@@ -139,17 +179,20 @@ namespace pacs_win_uia.Models
"Value", "Text", Selected, "IsSelected", Focused, "HasKeyboardFocus"
};
+ // Msaa:MSAA 来源可读取的属性键列表。
public static readonly IList Msaa = new List
{
"accName", "accValue", "accRole", "accState", "accDescription", "accDefaultAction", "PathKey",
Selected, Focused
};
+ // Win32:Win32 来源可读取的属性键列表。
public static readonly IList Win32 = new List
{
"窗口标题", "类名", "HWND", "窗口矩形", "客户区矩形", "可见", "最小化", "进程名", "PID", Focused
};
+ // For:按来源偏好给出建议键;Auto 返回三来源的并集,末尾附加 OCR 文本键。
/// Suggested keys for a source preference (Auto = the union of all three).
public static IList For(ControlSourcePreference preference)
{
@@ -173,6 +216,7 @@ namespace pacs_win_uia.Models
return keys;
}
+ // ForSource:按实际快照来源给出键列表,并确保包含 OCR 文本键。
public static IList ForSource(ControlTreeSource source)
{
IList keys;
diff --git a/src/pacs_win_uia/Models/ControlMonitorDefinition.cs b/src/pacs_win_uia/Models/ControlMonitorDefinition.cs
index e45be84..2a4dda1 100644
--- a/src/pacs_win_uia/Models/ControlMonitorDefinition.cs
+++ b/src/pacs_win_uia/Models/ControlMonitorDefinition.cs
@@ -5,9 +5,28 @@ using System.Runtime.Serialization;
namespace pacs_win_uia.Models
{
+ // ============================================================================
+ // ControlMonitorDefinition —— 一条“控件监控”定义(也是配置文件 control-monitors.json 的条目)。
+ //
+ // 职责:描述要监控什么(窗口 + 路径 + 可选取值键)以及它的开关 / 超时等设置。
+ //
+ // 被谁调用:ControlMonitorStore(读写)、ControlLocatorService(重新定位)、监控编辑界面与无界面监控。
+ //
+ // 字段可空语义(重点):
+ // - ControlPath:权威定位(XPath),必须有值;旧字段 UiaPath/MsaaPathKey/Win32Path 只作显示。
+ // - PageFeatures:空 = 重新定位时不校验页面(仅按窗口三要素 + 路径定位)。
+ // - ValueKey:空 = 只定位不取值;填写则必须是合法的属性键。
+ // - RuntimeId/FocusState/Value:动态或提示性字段,不持久化(见 [IgnoreDataMember])。
+ // - Source/Enabled:以友好的强类型形式暴露,实际分别持久化为 SourceName 字符串与 Disabled 布尔。
+ //
+ // 校验规则:由 ControlMonitorRules 提供,本类通过 IDataErrorInfo 逐字段暴露,供编辑网格即时提示。
+ //
+ // 要改什么就改哪里:新增或改名持久化字段时,需同步 ControlMonitorStore.CopyDefinition 与 ControlMonitorRules.Fields。
+ // ============================================================================
[DataContract]
public sealed class ControlMonitorDefinition : IDataErrorInfo
{
+ // 构造:生成新的 GUID、默认 Auto 来源,并初始化两个旧段列表。
public ControlMonitorDefinition()
{
Id = Guid.NewGuid().ToString("N");
@@ -16,20 +35,25 @@ namespace pacs_win_uia.Models
Win32Path = new List();
}
+ // Id:条目标识(非空 GUID 字符串),配置里必须唯一。
[DataMember(Order = 1, IsRequired = true)]
public string Id { get; set; }
+ // ControlPath:权威 XPath 1.0(在所选来源快照上执行);旧 path 文本仅作显示。
/// Authoritative XPath 1.0 over the selected source snapshot. Legacy text is display-only.
[DataMember(Order = 2, IsRequired = false, EmitDefaultValue = false)]
public string ControlPath { get; set; }
+ // PageFeatures:可选;为空表示重新定位时不校验页面。
/// Optional: empty means "do not check the page" when re-resolving.
[DataMember(Order = 3, IsRequired = false, EmitDefaultValue = false)]
public string PageFeatures { get; set; }
+ // ContentKey:别名键,供导出 / 脚本引用该条目;配置内区分大小写且不能重复。
[DataMember(Order = 4, IsRequired = false, EmitDefaultValue = false)]
public string ContentKey { get; set; }
+ // RuntimeId:拾取时的 UIA RuntimeId,仅作定位线索(目标程序重启后失效),不持久化。
///
/// UIA runtime id of the control at capture time. It is a hint for re-resolution only:
/// runtime ids are not stable across a restart of the target application.
@@ -40,6 +64,7 @@ namespace pacs_win_uia.Models
// ---------------------------------------------------------------- re-resolution locator
// Legacy locator fields are retained only for loading/display; resolution uses ControlPath.
+ // SourceName:持久化的来源名称("Auto"/"Uia"/"Msaa"/"Win32"),便于手改文件且 JSON 兼容。
///
/// Persisted as a readable name ("Auto"/"Uia"/"Msaa"/"Win32") rather than a number: the
/// config file is meant to be hand-edited, and DataContractJsonSerializer would otherwise
@@ -48,6 +73,7 @@ namespace pacs_win_uia.Models
[DataMember(Order = 6, Name = "Source", IsRequired = false, EmitDefaultValue = false)]
public string SourceName { get; set; }
+ // Source:SourceName 的强类型视图;解析失败按 Auto 处理。
[IgnoreDataMember]
[Description("XPath 快照来源:自动先选可用来源(UIA→MSAA→Win32);显式来源不跨来源回退。")]
public ControlSourcePreference Source
@@ -56,6 +82,7 @@ namespace pacs_win_uia.Models
set { SourceName = value.ToString(); }
}
+ // ParseSourcePreference:把 SourceName 解析成枚举;空值 / 未知值回落 Auto,也容忍旧的数字写法。
private static ControlSourcePreference ParseSourcePreference(string value)
{
if (string.IsNullOrEmpty(value))
@@ -81,39 +108,48 @@ namespace pacs_win_uia.Models
}
}
+ // ProcessName:目标进程名,用于无 HWND 时找回顶层窗口。
[DataMember(Order = 7, IsRequired = false, EmitDefaultValue = false)]
[Description("目标进程名,用来在不依赖 HWND 的情况下找到顶层窗口。")]
public string ProcessName { get; set; }
+ // WindowClass:顶层窗口类名,配合进程名与标题关键词定位窗口。
[DataMember(Order = 8, IsRequired = false, EmitDefaultValue = false)]
[Description("顶层窗口类名,配合进程名与标题关键词定位顶层窗口。")]
public string WindowClass { get; set; }
+ // WindowTitleKeyword:顶层窗口标题关键词(包含匹配);三项都填时最精确。
[DataMember(Order = 9, IsRequired = false, EmitDefaultValue = false)]
[Description("顶层窗口标题关键词(包含匹配)。三个都填时匹配最精确。")]
public string WindowTitleKeyword { get; set; }
+ // UiaPath:旧 UIA 结构化路径(仅显示,不执行)。
[DataMember(Order = 10, IsRequired = false, EmitDefaultValue = false)]
[Description("旧 UIA 结构化路径(仅保留显示,不执行;请重新拾取生成 XPath)。")]
public List UiaPath { get; set; }
+ // MsaaPathKey:旧 MSAA 路径(仅显示,不执行)。
[DataMember(Order = 11, IsRequired = false, EmitDefaultValue = false)]
[Description("旧 MSAA 路径(仅保留显示,不执行;请重新拾取生成 XPath)。")]
public string MsaaPathKey { get; set; }
+ // UiaPathFromInnerWindow:旧标志,仅为兼容反序列化 / 显示保留,不参与定位或新保存。
/// Legacy flag retained only for deserialization/display, never executed.
[DataMember(Order = 17, IsRequired = false, EmitDefaultValue = false)]
[Description("旧内层窗口标志(不再参与定位或新保存)。")]
public bool UiaPathFromInnerWindow { get; set; }
+ // Win32Path:旧 Win32 结构化路径(仅显示,不执行)。
[DataMember(Order = 12, IsRequired = false, EmitDefaultValue = false)]
[Description("旧 Win32 结构化路径(仅保留显示,不执行;请重新拾取生成 XPath)。")]
public List Win32Path { get; set; }
+ // ValueKey:要读取的属性名(随来源不同);为空表示只定位不取值。
[DataMember(Order = 13, IsRequired = false, EmitDefaultValue = false)]
[Description("要读取的属性名。可选项随来源不同:UIA 用 Name/Value/Text 等,MSAA 用 accName/accValue 等,Win32 用 窗口标题/类名 等。留空表示只定位不取值。")]
public string ValueKey { get; set; }
+ // Disabled:持久化为 Disabled,使旧文件缺字段时默认“启用”。
///
/// Stored as "Disabled" so that a config written before this field exists means "enabled":
/// absent must not silently disable every saved control.
@@ -121,6 +157,7 @@ namespace pacs_win_uia.Models
[DataMember(Order = 15, Name = "Disabled", IsRequired = false, EmitDefaultValue = false)]
public bool Disabled { get; set; }
+ // Enabled:Disabled 的反相视图(界面用)。
[IgnoreDataMember]
[Description("该条监控是否启用。停用的条目仍保留在配置里,但无界面模式会跳过它。")]
public bool Enabled
@@ -129,6 +166,7 @@ namespace pacs_win_uia.Models
set { Disabled = !value; }
}
+ // FocusState:最近一次定位 / 刷新读到的焦点状态,不持久化(表示“此刻”而非定义)。
///
/// Focus state read by the editor's 定位/刷新 action. Not persisted: it describes "right now",
/// not the definition.
@@ -137,6 +175,7 @@ namespace pacs_win_uia.Models
[Description("最近一次定位/刷新读到的焦点状态(不保存,只表示当前状态)。")]
public string FocusState { get; set; }
+ // TimeoutSeconds:等待该控件出现的秒数;0 = 用全局 --timeout;每条独立计时。
///
/// How long to wait for this control when reading head-only. 0 means "use the global
/// --timeout". Each entry is timed on its own, so one control that never appears cannot eat
@@ -146,10 +185,12 @@ namespace pacs_win_uia.Models
[Description("等待该控件出现的秒数。0 = 使用全局 --timeout。每条独立计时,某个控件等不到不会拖累其他控件。")]
public int TimeoutSeconds { get; set; }
+ // Value:实时读到的值,不写入 JSON。
[IgnoreDataMember]
[Description("实时读取的值,不写入监控定义 JSON。")]
public string Value { get; set; }
+ // IDataErrorInfo.Error:返回第一个字段错误(供绑定校验使用)。
string IDataErrorInfo.Error
{
get
@@ -167,11 +208,13 @@ namespace pacs_win_uia.Models
}
}
+ // IDataErrorInfo 索引器:返回指定字段的校验信息。
string IDataErrorInfo.this[string columnName]
{
get { return ControlMonitorRules.ValidateField(this, columnName); }
}
+ // ToString:优先显示 ContentKey,否则显示 ControlPath。
public override string ToString()
{
return string.IsNullOrEmpty(ContentKey) ? ControlPath : ContentKey;
diff --git a/src/pacs_win_uia/Models/ControlMonitorRules.cs b/src/pacs_win_uia/Models/ControlMonitorRules.cs
index 74c0220..46ed8cc 100644
--- a/src/pacs_win_uia/Models/ControlMonitorRules.cs
+++ b/src/pacs_win_uia/Models/ControlMonitorRules.cs
@@ -5,8 +5,10 @@ using pacs_win_uia.Services;
namespace pacs_win_uia.Models
{
+ // ControlMonitorValidationError:一条校验错误(位置 + 字段 + 信息)。
public sealed class ControlMonitorValidationError
{
+ // 构造:记录出错行下标、字段名与信息。
public ControlMonitorValidationError(int index, string fieldName, string message)
{
Index = index;
@@ -14,13 +16,17 @@ namespace pacs_win_uia.Models
Message = message;
}
+ // Index:列表内下标;-1 表示错误针对整份列表。
/// Index inside the definition list; -1 when the error is about the list itself.
public int Index { get; private set; }
+ // FieldName:出错字段名;为空表示不限字段。
public string FieldName { get; private set; }
+ // Message:错误说明。
public string Message { get; private set; }
+ // ToString:格式化成“第 N 行 字段:信息”或“整体:信息”。
public override string ToString()
{
string location = Index < 0 ? "整体" : "第 " + (Index + 1) + " 行";
@@ -30,25 +36,55 @@ namespace pacs_win_uia.Models
}
}
+ // ============================================================================
+ // ControlMonitorRules —— 监控定义的校验规则(store 与编辑界面共用同一套)。
+ //
+ // 职责:定义字段上限与格式规则,并逐条校验单个字段 / 整份列表,一次性返回所有问题。
+ //
+ // 被谁调用:ControlMonitorStore(Load 宽松、Save 严格)、ControlMonitorDefinition.IDataErrorInfo、
+ // 编辑器网格(TryValidate)——UI 可一次性列出所有问题,而不是一次抛一个异常。
+ //
+ // 关键校验语义(字段可空):
+ // - ControlPath:必须非空且语法合法的 XPath(复用 ControlPath.ValidateSyntax);
+ // Load 时可为旧格式豁免,Save / 界面则严格。
+ // - PageFeatures:空 = 不校验页面,故空合法,只限长度。
+ // - ValueKey:空 = 只定位不取值,故空合法;非空则限长度。
+ // - ContentKey:必填、必须 ASCII 标识符形状(不支持中文)、列表内区分大小写唯一。
+ // - Id:必须是非空 GUID 且列表内唯一;RuntimeId/Value 仅做长度限制。
+ //
+ // 要改什么就改哪里:上限常量与 Fields 列表;单字段规则在 ValidateField;跨行规则在 ValidateList。
+ // ============================================================================
+ // ControlMonitorRules:store 与编辑网格共用的校验规则。
///
/// Validation shared by the store and the editor grid, so the UI can show every problem at once
/// instead of surfacing one exception at a time.
///
public static class ControlMonitorRules
{
+ // MaxDefinitions:定义条数上限。
public const int MaxDefinitions = 500;
+ // MaxDocumentBytes:整份文档字节上限(1 MB)。
public const int MaxDocumentBytes = 1024 * 1024;
+ // MaxControlPathLength:ControlPath 字符数上限。
public const int MaxControlPathLength = 2048;
+ // MaxPageFeaturesLength:页面特征字符数上限。
public const int MaxPageFeaturesLength = 512;
+ // MaxContentKeyLength:别名键字符数上限。
public const int MaxContentKeyLength = 128;
+ // MaxRuntimeIdLength:RuntimeId 字符数上限。
public const int MaxRuntimeIdLength = 256;
+ // ContentKeyRule:别名键的字符规则(ASCII 标识符形状,字符串形式,供界面提示)。
public const string ContentKeyRule = "^[A-Za-z_][A-Za-z0-9_.-]*$";
+ // MaxValueKeyLength:属性名字符数上限。
public const int MaxValueKeyLength = 64;
+ // MaxValueLength:值字符数上限。
public const int MaxValueLength = 4096;
+ // ContentKeyRegex:别名键的编译后正则(与 ContentKeyRule 语义一致)。
private static readonly Regex ContentKeyRegex = new Regex(
@"\A[A-Za-z_][A-Za-z0-9_.-]*\z", RegexOptions.CultureInvariant);
+ // Fields:逐字段校验涉及的字段名列表。
private static readonly string[] Fields =
{
"Id",
@@ -60,11 +96,13 @@ namespace pacs_win_uia.Models
"Value"
};
+ // FieldNames:对外暴露字段名列表,供绑定 / 遍历校验使用。
public static IList FieldNames
{
get { return Fields; }
}
+ // ValidateField:校验单个字段;合法返回 null,否则返回中文错误说明。
/// Validates one field; returns null when the field is acceptable.
public static string ValidateField(ControlMonitorDefinition definition, string fieldName)
{
@@ -110,12 +148,15 @@ namespace pacs_win_uia.Models
}
}
+ // ValidateList:校验整份列表(严格模式),含跨行规则,返回发现的全部错误。
/// Validates the whole list, including rules that span rows. Returns every error found.
public static IList ValidateList(IList definitions)
{
return ValidateList(definitions, true);
}
+ // ValidateList(宽松重载):validatePathSyntax=false 时对 ControlPath 只查长度,
+ // 让旧格式 / 手改的路径仍可加载修复;保存与界面校验走上面的严格默认重载。
///
/// Validates a definition list. Loading uses false so
/// an old or hand-edited path remains available for repair instead of making the whole file
@@ -195,11 +236,13 @@ namespace pacs_win_uia.Models
return errors;
}
+ // Length:null 视为 0,否则取字符串长度。
private static int Length(string value)
{
return value == null ? 0 : value.Length;
}
+ // ValidateId:Id 必须是非空 GUID,否则返回错误。
private static string ValidateId(string id)
{
Guid parsed;
@@ -211,12 +254,15 @@ namespace pacs_win_uia.Models
return null;
}
+ // ValidateControlPath:先查非空与长度,再交给 ControlPath.ValidateSyntax 校验 XPath 语法;
+ // 供直改、多行编辑、PropertyGrid 与保存校验共用。
/// Shared by direct edits, the multiline editor, PropertyGrid and save validation.
public static string ValidateControlPath(string path)
{
return ValidateRequired(path, "控件 Path", MaxControlPathLength) ?? ControlPath.ValidateSyntax(path);
}
+ // ValidateRequired:通用“必填 + 长度”校验;空返回“不能为空”,过长返回“过长”。
private static string ValidateRequired(string value, string label, int maxLength)
{
if (string.IsNullOrWhiteSpace(value))
@@ -229,6 +275,7 @@ namespace pacs_win_uia.Models
: label + "过长(上限 " + maxLength + " 个字符)。";
}
+ // ValidateContentKey:别名键必填、限长且须匹配 ASCII 标识符正则(因最终进入 JSON 文档)。
private static string ValidateContentKey(string contentKey)
{
if (string.IsNullOrWhiteSpace(contentKey))
diff --git a/src/pacs_win_uia/Models/ControlTreeNode.cs b/src/pacs_win_uia/Models/ControlTreeNode.cs
index 1b91bd0..bc18ccf 100644
--- a/src/pacs_win_uia/Models/ControlTreeNode.cs
+++ b/src/pacs_win_uia/Models/ControlTreeNode.cs
@@ -5,6 +5,25 @@ using System.Runtime.Serialization;
namespace pacs_win_uia.Models
{
+ // ============================================================================
+ // ControlTreeNode —— 控件树的节点模型(UIA / MSAA / Win32 三个独立视图共用一种节点)。
+ //
+ // 职责:
+ // - ControlTreeSource:节点来自哪个无障碍来源(三来源互不合并);
+ // - ControlTreeNode:一个节点,组合对应来源的 payload(Uia / Msaa / Window),不做扁平化字段;
+ // - CanonicalPath:当前快照里算好的绝对 XPath(由 ControlPath.PreparePaths 预计算,不持久化);
+ // - ControlTreeOptions:所有读取器统一的边界(深度 / 节点数 / 超时等)。
+ //
+ // 被谁调用:ControlTreeService / 各 Reader 产出节点,ControlPath 生成路径,
+ // ControlLocatorBuilder / ControlLocatorService 定位,界面控件树与 PropertyGrid、导出器消费这些节点。
+ //
+ // 要改什么就改哪里:
+ // - 节点字段:ControlTreeNode 的属性;
+ // - 路径缓存字段:CanonicalPath / CanonicalPathRoot(真正算法在 ControlPath.PreparePaths);
+ // - 读取边界:ControlTreeOptions 的默认值。
+ //
+ // 关键语义:某个来源的 payload 为 null,表示该节点没有这个来源的数据(例如 Win32 节点的 Uia == null)。
+ // ============================================================================
///
/// Which accessibility source produced a node. The three are independent views of the same UI
/// and are never merged across sources.
@@ -12,16 +31,20 @@ namespace pacs_win_uia.Models
[DataContract]
public enum ControlTreeSource
{
+ // Uia:来自 UI Automation(Rich view)。
[EnumMember]
Uia,
+ // Msaa:来自 MSAA(IAccessible)。
[EnumMember]
Msaa,
+ // Win32:来自原生窗口(HWND 树)。
[EnumMember]
Win32
}
+ // ControlTreeNode:控件树的一个节点,按来源组合 payload;Children 是子节点列表。
///
/// One node of the control tree. It composes the existing per-source models instead of flattening
/// them, so the property grid, the exporters and the UIA-only actions keep working unchanged.
@@ -29,44 +52,55 @@ namespace pacs_win_uia.Models
[DataContract]
public sealed class ControlTreeNode
{
+ // 构造:初始化空 Children,并默认子节点完整。
public ControlTreeNode()
{
Children = new List();
ChildrenComplete = true;
}
+ // Source:节点来源;三个来源是独立视图,不保证互相对应。
[DataMember(Order = 1)]
[Description("该节点来自哪个来源:UIA / MSAA / Win32。三个来源是独立视图,不保证互相对应。")]
public ControlTreeSource Source { get; set; }
+ // Uia:仅 UIA 节点有;承载完整 UIA 属性负载(工具其余部分已在用的快照)。
/// UIA nodes only: the rich snapshot the rest of the tool already uses.
[DataMember(Order = 2)]
public UiaElementInfo Uia { get; set; }
+ // Msaa:仅 MSAA 节点有。
/// MSAA nodes only.
[DataMember(Order = 3)]
public MsaaNodeInfo Msaa { get; set; }
+ // Window:仅 Win32 节点有;承载 HWND、类名、矩形。
/// Win32 nodes only: HWND, class name, rectangles.
[DataMember(Order = 4)]
public NativeWindowInfo Window { get; set; }
+ // Children:子节点列表(顺序即树的顺序)。
[DataMember(Order = 5)]
public List Children { get; private set; }
+ // ChildrenComplete:该节点的子节点是否读取完整;false 表示可能漏读。
[DataMember(Order = 6)]
public bool ChildrenComplete { get; set; }
+ // ChildrenError:子节点读取不完整时的原因说明。
[DataMember(Order = 7)]
public string ChildrenError { get; set; }
+ // CanonicalPath:当前快照里预计算好的绝对 XPath(含窗口根);由 ControlPath.PreparePaths 填充,不持久化。
/// Prepared absolute XPath in the current snapshot; not persisted.
[IgnoreDataMember]
public string CanonicalPath { get; internal set; }
+ // CanonicalPathRoot:该路径对应的根节点;用于判断缓存是否对应当前快照。
[IgnoreDataMember]
internal ControlTreeNode CanonicalPathRoot { get; set; }
+ // UiaElement:便捷访问——UIA 节点返回 Uia,否则返回 null。
[Browsable(false)]
[IgnoreDataMember]
public UiaElementInfo UiaElement
@@ -74,6 +108,7 @@ namespace pacs_win_uia.Models
get { return Source == ControlTreeSource.Uia ? Uia : null; }
}
+ // Describe:返回带来源前缀的树标签(UIA/MSAA/Win32),避免把 Win32 节点误当成控件。
/// Tree label. The source is always visible so a Win32-only node cannot be mistaken for a control.
public string Describe()
{
@@ -88,6 +123,7 @@ namespace pacs_win_uia.Models
}
}
+ // DescribeWindow:Win32 节点的显示文本(类名:标题 句柄 [隐藏][最小化])。
private string DescribeWindow()
{
if (Window == null)
@@ -116,15 +152,18 @@ namespace pacs_win_uia.Models
return builder.ToString();
}
+ // ToString:等价于 Describe()。
public override string ToString()
{
return Describe();
}
}
+ // ControlTreeOptions:所有读取器的边界,任何来源都不允许无界读取。
/// Bounds for every reader: no source may run unbounded.
public sealed class ControlTreeOptions
{
+ // 构造:设置默认边界(深度 12、节点 3000、超时 10 秒、每个 MSAA 节点子项 400 等)。
public ControlTreeOptions()
{
MaxDepth = 12;
@@ -135,18 +174,24 @@ namespace pacs_win_uia.Models
TitleReadTimeoutMs = 200;
}
+ // MaxDepth:树的最大深度。
public int MaxDepth { get; set; }
+ // MaxNodes:节点总数上限。
public int MaxNodes { get; set; }
+ // Timeout:整棵树读取的超时时间。
public TimeSpan Timeout { get; set; }
+ // MaxMsaaChildrenPerNode:单个 MSAA 节点的子节点上限;超大会截断并标记。
/// Upper bound for one MSAA node's children; huge lists are truncated and flagged.
public int MaxMsaaChildrenPerNode { get; set; }
+ // ReadWindowTitles:是否读取窗口标题(跨进程 WM_GETTEXT,可跳过)。
/// Window titles need a cross-process WM_GETTEXT; they can be skipped.
public bool ReadWindowTitles { get; set; }
+ // TitleReadTimeoutMs:单次读取窗口标题的超时(毫秒)。
public int TitleReadTimeoutMs { get; set; }
}
}
diff --git a/src/pacs_win_uia/Models/FloatingBarDefinition.cs b/src/pacs_win_uia/Models/FloatingBarDefinition.cs
index 40f4d45..04000bf 100644
--- a/src/pacs_win_uia/Models/FloatingBarDefinition.cs
+++ b/src/pacs_win_uia/Models/FloatingBarDefinition.cs
@@ -1,4 +1,19 @@
-using System;
+// ============================================================================
+// FloatingBarDefinition.cs —— 悬浮条的数据模型(配置的可序列化结构)
+// 职责:描述「一条悬浮条」及其「按钮」:位置(相对锚定窗口)、显示条件(进程名/窗口类/标题
+// 关键词,以及可选导入的控件 path)、外观(透明度/偏移)和可点击按钮。
+// 被谁调用:
+// · 持久化:序列化为 settings.json(DataContractJsonSerializer);
+// · SettingsForm「悬浮按钮」页负责编辑;
+// · FloatingBarManager 负责按这些定义创建/显示/隐藏实际悬浮条并执行按钮操作;
+// · CommandRunner / 悬浮条本身按 Shortcut 注册全局热键。
+// 默认值陷阱(务必注意):
+// · DataContractJsonSerializer 反序列化时【不会调用构造函数】,所以缺字段时的默认值靠
+// [OnDeserializing] 回调补齐(见 FloatingButtonDefinition / FloatingBarDefinition)。
+// · 按钮缺 Enabled 字段时视为 true(OnDeserializing 里先置 true)。
+// · 加了 EmitDefaultValue=false 的字段,取默认值时不写入 JSON → 老配置里可能整段缺失。
+// ============================================================================
+using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
@@ -6,68 +21,88 @@ using System.Windows.Forms;
namespace pacs_win_uia.Models
{
+ // 按钮「点击执行操作」的枚举;序列化进 settings.json。None 表示不执行任何操作。
[DataContract]
public enum FloatingActionKind
{
+ // 不执行任何操作(校验时会被 ConfigurationError 判为无效的按钮操作)。
[EnumMember]
None,
+ // 读取当前选中控件的列表内容。
[EnumMember]
ReadList,
+ // 按保存的 path 定位到目标控件(主界面高亮)。
[EnumMember]
LocateControl,
+ // 刷新监控项状态。
[EnumMember]
RefreshStates,
+ // 检查(读取)当前选中窗口的信息。
[EnumMember]
InspectWindow,
+ // 进入拾取控件模式,点哪个控件就记录哪个。
[EnumMember]
PickControl,
+ // 对当前窗口截图。
[EnumMember]
Screenshot,
+ // 对当前控件做 OCR 读取(控件原生读不到内容时才用)。
[EnumMember]
OcrRead,
+ // 执行该按钮自己的命令行(CommandLine 字段)。
/// Runs the button's own command line.
[EnumMember]
RunCommand
}
+ // 悬浮按钮页「点击执行操作」下拉的一项:枚举值 + 中文描述。
+ // 为什么需要它:网格列必须「显示中文名、但写回的是枚举」——直接绑枚举会显示 "PickControl"。
///
/// One entry of the settings dialog's "点击执行操作" dropdown: the enum value plus its Chinese name.
/// The grid must show the Chinese name while still writing the enum into the model.
///
public sealed class FloatingActionChoice
{
+ // 构造一项:value 写回模型,display 给操作员看。
public FloatingActionChoice(FloatingActionKind value, string display)
{
Value = value;
Display = display;
}
+ // 实际写入模型的枚举值(下拉的 ValueMember)。
public FloatingActionKind Value { get; private set; }
+ // 界面上显示的中文名(下拉的 DisplayMember)。
public string Display { get; private set; }
+ // 列表渲染默认走 ToString(),返回中文名。
public override string ToString()
{
return Display;
}
}
+ // 悬浮条上的一个按钮:显示名、点击操作、可选的命令行与全局快捷键、是否启用。
[DataContract]
public sealed class FloatingButtonDefinition
{
+ // 正常构造(代码里 new 出来的)默认启用。
public FloatingButtonDefinition()
{
Enabled = true;
}
+ // 反序列化时先补默认值:Enabled 缺省视为 true。
+ // 明确保存了 false 的配置,会在本回调之后被赋回,所以仍然生效。
[OnDeserializing]
private void OnDeserializing(StreamingContext context)
{
@@ -76,6 +111,7 @@ namespace pacs_win_uia.Models
Enabled = true;
}
+ // 校验按钮配置是否可用:返回错误文案,合法时返回 null。保存前会逐条检查。
[IgnoreDataMember]
public string ConfigurationError
{
@@ -89,31 +125,38 @@ namespace pacs_win_uia.Models
}
}
+ // 按钮上显示的文字;为空时 ToString() 回退到操作名。
[DataMember(Order = 1)]
[Description("按钮上显示的名称。")]
public string Label { get; set; }
+ // 点击时执行的操作,默认枚举值 None(无操作);保存校验会拒绝 None。
[DataMember(Order = 2)]
[Description("点击时执行的操作。")]
public FloatingActionKind Action { get; set; }
+ // 仅当 Action=RunCommand 时使用;EmitDefaultValue=false → 空白时不写入 JSON。
[DataMember(Order = 3, EmitDefaultValue = false)]
[Description("点击时执行的命令行(操作选“执行命令”时使用)。通过 cmd.exe /c 以当前用户身份运行。")]
public string CommandLine { get; set; }
+ // 全局热键(如 Ctrl+Alt+1 / F9);留空不注册。EmitDefaultValue=false → 空时不写入 JSON。
[DataMember(Order = 4, EmitDefaultValue = false)]
[Description("快捷键,例如 Ctrl+Alt+1 或 F9。留空表示不注册。注册冲突时会记日志。")]
public string Shortcut { get; set; }
+ // 是否启用该按钮。注意:老配置缺这个字段时由 OnDeserializing 补成 true(视为启用)。
[DataMember(Order = 5)]
[Description("是否启用该按钮。")]
public bool Enabled { get; set; }
+ // 列表/提示里显示按钮:优先中文名称,没填就用操作名。
public override string ToString()
{
return string.IsNullOrEmpty(Label) ? Action.ToString() : Label;
}
+ // 返回设置页下拉里可选的按钮操作(带中文名),顺序即下拉显示顺序。
///
/// The actions a floating button can run, in the order the settings dialog offers them, each
/// with the Chinese name the operator sees.
@@ -140,6 +183,7 @@ namespace pacs_win_uia.Models
return choices;
}
+ // 把单个操作枚举翻译成中文名(下拉与状态提示共用)。
public static string DescribeAction(FloatingActionKind kind)
{
switch (kind)
@@ -166,6 +210,8 @@ namespace pacs_win_uia.Models
}
}
+ // 一条悬浮条:相对锚定窗口的落点、显示条件与按钮集合。它会跟随锚定窗口,
+ // 所以偏移量是相对窗口左上角,而不是屏幕坐标。
///
/// One floating bar: where it sits (relative to its anchor window), when it is shown, and which
/// buttons it offers. It follows the anchor window, so the XY offsets are relative to that window's
@@ -174,11 +220,13 @@ namespace pacs_win_uia.Models
[DataContract]
public sealed class FloatingBarDefinition
{
+ // 正常构造:填默认值。
public FloatingBarDefinition()
{
SetDefaults();
}
+ // 统一的默认值:启用、不透明度 90、偏移 8/8、要求窗口可见、按钮列表非空。
private void SetDefaults()
{
Enabled = true;
@@ -189,18 +237,21 @@ namespace pacs_win_uia.Models
Buttons = new List();
}
+ // 反序列化不调用构造函数 → 这里补默认值(含「缺 Enabled 视为 true」的语义)。
[OnDeserializing]
private void OnDeserializing(StreamingContext context)
{
SetDefaults();
}
+ // 反序列化后再兜底一次:保证 Buttons 一定非 null(老配置里可能整段缺失)。
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
if (Buttons == null) Buttons = new List();
}
+ // 已启用按钮的数量(不序列化,仅计算)。
[IgnoreDataMember]
public int EnabledButtonCount
{
@@ -213,6 +264,8 @@ namespace pacs_win_uia.Models
}
}
+ // 整条悬浮条的配置校验:无启用按钮、或某个启用按钮自身配置有误时返回错误文案,否则 null。
+ // 只会检查「已启用」的按钮,不去动用户故意停用的按钮(Do not silently turn them back on)。
/// Do not silently turn intentionally disabled buttons back on.
[IgnoreDataMember]
public string ButtonConfigurationError
@@ -227,6 +280,8 @@ namespace pacs_win_uia.Models
}
}
+ // 导入监控项条件到一条没有任何启用按钮的悬浮条时,自动补一个「定位控件」按钮,
+ // 否则这条条即使显示出来也无事可做;返回是否真的补了按钮。
/// Importing a condition into an empty bar also gives it a real, editable action.
public bool EnsureButtonForImport()
{
@@ -236,17 +291,21 @@ namespace pacs_win_uia.Models
return true;
}
+ // 悬浮条名称;只用于界面显示,不参与匹配或定位。
[DataMember(Order = 1)]
public string Name { get; set; }
+ // 是否启用这条悬浮条(停用的条不会显示)。默认 true(见 SetDefaults)。
[DataMember(Order = 2)]
[Description("是否启用这条悬浮条。")]
public bool Enabled { get; set; }
+ // 整体不透明度百分比(20-100);背景/按钮的专用透明度留 0 时沿用它。默认 90。
[DataMember(Order = 3)]
[Description("悬浮条整体不透明度(20-100)。下面是背景/按钮各自的透明度;留 0 表示沿用这个值。")]
public int OpacityPercent { get; set; }
+ // 背景专用透明度(0-100);0 表示未设置,实际用 OpacityPercent(0% 本来也看不见)。
///
/// The bar is drawn by the tool itself (a layered window), so the background and the buttons can
/// have different transparency. 0 means "not set" and falls back to OpacityPercent — 0% would be
@@ -256,43 +315,53 @@ namespace pacs_win_uia.Models
[Description("背景透明度(0-100,留 0 = 用「透明度」)。")]
public int BackgroundOpacityPercent { get; set; }
+ // 按钮(控件)专用透明度(0-100);0 表示沿用 OpacityPercent。
[DataMember(Order = 11, EmitDefaultValue = false)]
[Description("按钮(控件)透明度(0-100,留 0 = 用「透明度」)。")]
public int ControlOpacityPercent { get; set; }
+ // 实际生效的背景透明度:取专用值,未设置则回退整体透明度(至少 1)。
[IgnoreDataMember]
public int EffectiveBackgroundOpacity
{
get { return BackgroundOpacityPercent > 0 ? BackgroundOpacityPercent : Math.Max(1, OpacityPercent); }
}
+ // 实际生效的按钮透明度:同上逻辑。
[IgnoreDataMember]
public int EffectiveControlOpacity
{
get { return ControlOpacityPercent > 0 ? ControlOpacityPercent : Math.Max(1, OpacityPercent); }
}
+ // 相对锚定窗口左上角的 X 偏移(像素),默认 8。
[DataMember(Order = 4)]
[Description("相对锚定窗口左上角的 X 偏移。")]
public int OffsetX { get; set; }
+ // 相对锚定窗口左上角的 Y 偏移(像素),默认 8。
[DataMember(Order = 5)]
[Description("相对锚定窗口左上角的 Y 偏移。")]
public int OffsetY { get; set; }
// ---- when to show
+ // 显示条件三件套之一:目标进程名。留空表示不用该条件。EmitDefaultValue=false → 空时不写入 JSON。
[DataMember(Order = 6, EmitDefaultValue = false)]
[Description("显示条件:目标进程名。")]
public string ProcessName { get; set; }
+ // 显示条件三件套之一:窗口类名(区分大小写,见 WindowMatcher)。
[DataMember(Order = 7, EmitDefaultValue = false)]
[Description("显示条件:窗口类名。")]
public string WindowClass { get; set; }
+ // 显示条件三件套之一:标题关键词(包含匹配、忽略大小写)。
[DataMember(Order = 8, EmitDefaultValue = false)]
[Description("显示条件:标题关键词。")]
public string WindowTitleKeyword { get; set; }
+ // 从监控项「导入 path」进来的控件定位条件副本:控件存在时该条才显示。
+ // 注意是副本(CopyCondition 深拷贝),监控项后续停用/修改不影响这里。
///
/// A control locator imported from a monitor entry ("导入 path"): the bar also waits for that
/// control to exist on the page.
@@ -300,19 +369,24 @@ namespace pacs_win_uia.Models
[DataMember(Order = 9, EmitDefaultValue = false)]
public ControlMonitorDefinition ImportedCondition { get; set; }
+ // 是否要求锚定窗口可见(未最小化且未被遮挡)才显示;默认 true。
[DataMember(Order = 12)]
[Description("锚定窗口必须可见(未最小化且没有被遮挡)时才显示。")]
public bool RequireWindowVisible { get; set; }
+ // 这条悬浮条的所有按钮。反序列化后由 OnDeserialized 保证非 null。
[DataMember(Order = 13)]
public List Buttons { get; set; }
+ // 列表里显示这条悬浮条:名称 + 启停状态 + 启用按钮数。
public override string ToString()
{
string name = string.IsNullOrEmpty(Name) ? "(未命名悬浮条)" : Name;
return name + "(" + (Enabled ? "启用" : "停用") + "," + EnabledButtonCount + " 个启用按钮)";
}
+ // 解析 "Ctrl+Alt+1" / "F9" / "Shift+F2" 这类快捷键文本,输出 Win32 热键的修饰键位与虚拟键码;
+ // 解析失败时通过 error 返回中文原因(保存前会用它弹提示,避免静默注册不上)。
///
/// Parses "Ctrl+Alt+1" / "F9" / "Shift+F2" into Win32 hotkey parts.
///
@@ -336,6 +410,7 @@ namespace pacs_win_uia.Models
continue;
}
+ // 修饰键(不区分大小写)叠加到修饰键位;不认识的词留作主键。
if (string.Equals(token, "Ctrl", StringComparison.OrdinalIgnoreCase) ||
string.Equals(token, "Control", StringComparison.OrdinalIgnoreCase))
{
@@ -365,6 +440,7 @@ namespace pacs_win_uia.Models
return false;
}
+ // 单字符主键:字母 A-Z 或数字 0-9 直接作为虚拟键码。
if (key.Length == 1)
{
char character = char.ToUpperInvariant(key[0]);
@@ -381,6 +457,7 @@ namespace pacs_win_uia.Models
}
}
+ // F1-F24 主键:映射到 VK_F1(0x70) 起的虚拟键码。
if (key.Length >= 2 && (key[0] == 'F' || key[0] == 'f'))
{
int index;
@@ -395,11 +472,16 @@ namespace pacs_win_uia.Models
return false;
}
+ // 全局热键的修饰键位(对应 Win32 RegisterHotKey 的 MOD_* 常量)。
public static class NativeModifiers
{
+ // MOD_ALT
public const uint Alt = 0x0001;
+ // MOD_CONTROL
public const uint Control = 0x0002;
+ // MOD_SHIFT
public const uint Shift = 0x0004;
+ // MOD_WIN
public const uint Win = 0x0008;
}
}
diff --git a/src/pacs_win_uia/Models/HeadlessReport.cs b/src/pacs_win_uia/Models/HeadlessReport.cs
index 10d6884..de7bdd0 100644
--- a/src/pacs_win_uia/Models/HeadlessReport.cs
+++ b/src/pacs_win_uia/Models/HeadlessReport.cs
@@ -2,12 +2,23 @@ using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
+// ============================================================================
+// HeadlessReport.cs —— 无界面读取的报告数据模型(序列化为 JSON)
+// 职责:承载一次 headless 读取的完整结果:元数据、统计汇总、搜索空间窗口列表、逐条结果。
+// 被谁调用:HeadlessConfigReader.Read 负责构造与填充,随后序列化输出给命令行调用方。
+// 数据契约:全部是 [DataContract]/[DataMember];标了 EmitDefaultValue=false 的字段在默认值时不写入 JSON。
+// 统计口径见 HeadlessSummary 各字段注释;总原则是不伪造数据:未定位、取不到值、停用跳过如实区分。
+// 要改什么就改哪里:新增/调整输出字段改对应数据类即可;若改统计含义,要同步 HeadlessConfigReader
+// 结尾的汇总循环,以及本文件 Summary 字段的注释。
+// ============================================================================
namespace pacs_win_uia.Models
{
/// Result document of one headless (no UI) read of a saved monitor config.
+ /// 一次无界面读取的顶层报告文档。
[DataContract]
public sealed class HeadlessReport
{
+ // 构造:初始化各集合,避免使用方遇到 null。
public HeadlessReport()
{
Windows = new List();
@@ -15,156 +26,203 @@ namespace pacs_win_uia.Models
Summary = new HeadlessSummary();
}
+ // 读取发生的 UTC 时间。
[DataMember(Order = 1)]
public DateTime ReadAtUtc { get; set; }
+ // 本次读取所用的配置文件路径。
[DataMember(Order = 2)]
public string ConfigPath { get; set; }
+ // 整个读取过程的总耗时(毫秒)。
[DataMember(Order = 3)]
public long ElapsedMs { get; set; }
+ // 统计汇总(命中/未定位/取不到值/跳过)。
[DataMember(Order = 4)]
public HeadlessSummary Summary { get; set; }
+ // 读取时可见的顶层窗口列表 —— 即搜索空间,用于事后诊断。
/// Visible top-level windows seen at read time — the search space, for diagnosis.
[DataMember(Order = 5)]
public List Windows { get; set; }
+ // 逐条定义的结果列表。
[DataMember(Order = 6)]
public List Items { get; set; }
+ // 本次读取是否跳过了已停用的定义。
[DataMember(Order = 7)]
public bool SkipDisabled { get; set; }
}
+ // 一次读取的统计汇总。
[DataContract]
public sealed class HeadlessSummary
{
+ // 配置里的定义总数。
[DataMember(Order = 1)]
public int Total { get; set; }
+ // 定位到且取到值(以及未设 ValueKey 的“仅定位”条目)的数量。
/// Controls that were located and whose value was read.
[DataMember(Order = 2)]
public int Found { get; set; }
+ // 完全没能定位到的数量。
/// Controls that could not be located at all.
[DataMember(Order = 3)]
public int Missing { get; set; }
+ // 定位到了但值读不出来的数量(仅统计设了 ValueKey 的条目)。
/// Controls that were located but whose value could not be read.
[DataMember(Order = 4)]
public int ValueUnavailable { get; set; }
+ // 配置里处于停用状态、被有意跳过的条目数。
/// Entries left disabled in the config, so deliberately not read.
[DataMember(Order = 5)]
public int Skipped { get; set; }
+ // 注意:这里原先有一条孤立的 XML 文档注释(没有对应成员),未做改动。
/// Whether disabled definitions were skipped for this report.
}
+ // 读取时一个顶层窗口的快照(搜索空间的组成项)。
[DataContract]
public sealed class HeadlessWindowInfo
{
+ // 窗口句柄(十六进制字符串)。
[DataMember(Order = 1)]
public string Hwnd { get; set; }
+ // 所属进程名。
[DataMember(Order = 2)]
public string ProcessName { get; set; }
+ // 所属进程 ID。
[DataMember(Order = 3)]
public int ProcessId { get; set; }
+ // 窗口类名。
[DataMember(Order = 4)]
public string ClassName { get; set; }
+ // 窗口标题。
[DataMember(Order = 5)]
public string Title { get; set; }
}
+ // 单条定义的读取结果。
[DataContract]
public sealed class HeadlessItemResult
{
+ // 内容键(业务标识)。
[DataMember(Order = 1)]
public string ContentKey { get; set; }
+ // 控件路径(定位用的表达式)。
[DataMember(Order = 2)]
public string ControlPath { get; set; }
+ // 页面特征(用于区分同进程的不同页面)。
[DataMember(Order = 3)]
public string PageFeatures { get; set; }
+ // 配置里请求的定位来源(Win32/UIA/MSAA)。
[DataMember(Order = 4)]
public string RequestedSource { get; set; }
+ // 实际定位成功所用的来源(发生回退时可能与请求的不同,可能为 null)。
/// Source that actually located the control (may differ when falling back).
[DataMember(Order = 5)]
public string ResolvedSource { get; set; }
+ // 控件本身是否被定位到。
/// Whether the control itself was located.
[DataMember(Order = 6)]
public bool Found { get; set; }
+ // 实际使用的取值键(OCR 降级成功时会被改成 OcrText)。
[DataMember(Order = 7)]
public string ValueKey { get; set; }
+ // 取到的值(OCR 降级来的值也放在这里)。
[DataMember(Order = 8)]
public string Value { get; set; }
+ // 值是否可用;定位到控件但读不出值时为 false。
/// False when the control was found but its value could not be read.
[DataMember(Order = 9)]
public bool ValueAvailable { get; set; }
+ // 导出出来的控件属性快照。
[DataMember(Order = 10)]
public HeadlessAttributes Attributes { get; set; }
+ // 逐步骤的定位日志,便于不用调试器就能排查“为什么没找到”。
/// Step-by-step log of the resolution, so a miss can be diagnosed without a debugger.
[DataMember(Order = 11)]
public List Resolution { get; set; }
+ // 该条目的错误信息(未定位 / 取值失败等)。
[DataMember(Order = 12)]
public string Error { get; set; }
+ // 该条目自身耗时(毫秒)。
[DataMember(Order = 13)]
public long ElapsedMs { get; set; }
}
+ // 控件属性快照:不同来源(UIA/MSAA/Win32)能填的字段不同,未填的字段默认值时不写入 JSON。
[DataContract]
public sealed class HeadlessAttributes
{
+ // 控件名称。
[DataMember(Order = 1, EmitDefaultValue = false)]
public string Name { get; set; }
+ // UIA 控件类型。
[DataMember(Order = 2, EmitDefaultValue = false)]
public string ControlType { get; set; }
+ // 窗口/控件类名。
[DataMember(Order = 3, EmitDefaultValue = false)]
public string ClassName { get; set; }
+ // MSAA 角色文本。
[DataMember(Order = 4, EmitDefaultValue = false)]
public string Role { get; set; }
+ // UIA AutomationId。
[DataMember(Order = 5, EmitDefaultValue = false)]
public string AutomationId { get; set; }
+ // 所属窗口标题。
[DataMember(Order = 6, EmitDefaultValue = false)]
public string WindowTitle { get; set; }
+ // 所属进程名。
[DataMember(Order = 7, EmitDefaultValue = false)]
public string ProcessName { get; set; }
+ // 所属进程 ID。
[DataMember(Order = 8)]
public int ProcessId { get; set; }
+ // 关联的窗口句柄(十六进制字符串)。
[DataMember(Order = 9, EmitDefaultValue = false)]
public string Hwnd { get; set; }
+ // 包围盒。
[DataMember(Order = 10, EmitDefaultValue = false)]
public string Bounds { get; set; }
+ // 是否在屏幕外(可为空表示未知)。
[DataMember(Order = 11, EmitDefaultValue = false)]
public bool? IsOffscreen { get; set; }
+ // 是否可用/启用(可为空表示未知)。
[DataMember(Order = 12, EmitDefaultValue = false)]
public bool? IsEnabled { get; set; }
}
diff --git a/src/pacs_win_uia/Models/ListReadModels.cs b/src/pacs_win_uia/Models/ListReadModels.cs
index a38f128..b28042f 100644
--- a/src/pacs_win_uia/Models/ListReadModels.cs
+++ b/src/pacs_win_uia/Models/ListReadModels.cs
@@ -1,39 +1,74 @@
+// ===========================================================================
+// ListReadModels —— 列表读取的数据模型(DTO)
+//
+// 职责:定义“读取列表”链路的输入选项与输出结果结构,并用 [DataContract]/[DataMember]
+// 固定字段顺序,保证 JSON 序列化跨版本可读、可回落。
+// 被谁调用:ListReaderService(产出 ListReadResult)、ListResultExporter(序列化导出)、
+// MainForm(展示/导出),单控件取值链路的 ControlValueReader 也复用 ListReadOptions。
+// 读取策略顺序:列表见 ListReaderService(UIA Grid/Table → 遍历降级);单个控件取值见
+// ControlValueReader(UIA → MSAA/Win32 → OCR)。
+// “找不到 ≠ 空列表”:读不到时以 Status=Unsupported/Failed + Error 表达,绝不返回 0 行的
+// “成功”结果来冒充空列表。
+// 预算与超时:ListReadOptions 中的 MaxRows/MaxColumns/Timeout/MaxTraversalNodes 等即预算与“软截止”。
+// 要扩展:新增字段请沿用递增的 [DataMember(Order = n)],不要打乱既有顺序(影响旧 JSON 兼容)。
+// ===========================================================================
+
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace pacs_win_uia.Models
{
+ // 列表读取的总体状态。
public enum ListReadStatus
{
+ // 完整读取成功。
Success,
+ // 部分成功:受上限截断、部分单元格读不到,或走了降级路径。
Partial,
+ // 目标没有暴露可读取的列表结构(找不到 ≠ 空列表)。
Unsupported,
+ // 读取过程抛出异常导致失败。
Failed,
+ // 被调用方取消。
Canceled,
+ // 超过软截止时间而停止。
TimedOut
}
+ // 本次结果实际采用的读取来源。
public enum ListReadSource
{
+ // 未知/未确定。
Unknown,
+ // 来自 UIA GridPattern。
UiaGridPattern,
+ // 来自 UIA TablePattern。
UiaTablePattern,
+ // 仅从 SelectionPattern 读到选中项(无行列数据)。
UiaSelectionPattern,
+ // 来自子元素遍历降级。
UiaElementTraversal
}
+ // 单元格值来自哪个属性/模式。
public enum ListValueSource
{
+ // 无来源(未取到值)。
None,
+ // 来自 ValuePattern。
ValuePattern,
+ // 来自 TextPattern。
TextPattern,
+ // 来自元素 Name。
Name
}
+ // 列表读取的输入选项(含各类上限、预算与软截止超时)。
[DataContract]
public sealed class ListReadOptions
{
+ // 构造时填入保守的默认上限:行 1000、列 200、超时 5 秒等。
public ListReadOptions()
{
MaxRows = 1000;
@@ -47,118 +82,153 @@ namespace pacs_win_uia.Models
MaxTextLength = 32768;
}
+ // 最多读取的行数(超出即截断并标记 Partial)。
[DataMember(Order = 1)]
public int MaxRows { get; set; }
+ // 最多读取的列数(超出即截断并标记 Partial)。
[DataMember(Order = 2)]
public int MaxColumns { get; set; }
+ // 软截止超时:同步 Provider 调用无法强制中断,只在检查点生效。
[DataMember(Order = 3)]
public TimeSpan Timeout { get; set; }
+ // 是否额外读取选中项(SelectionPattern)。
[DataMember(Order = 4)]
public bool ReadSelection { get; set; }
+ // 收集错误条数的上限(0 表示不限)。
[DataMember(Order = 5)]
public int MaxErrors { get; set; }
/// Node budget for the child-element traversal fallback.
+ // 子元素遍历降级的节点预算。
[DataMember(Order = 6)]
public int MaxTraversalNodes { get; set; }
/// How deep the traversal fallback may descend below the list container.
+ // 遍历降级从列表容器向下可下钻的最大层数。
[DataMember(Order = 7)]
public int MaxTraversalDepth { get; set; }
/// How many ancestors of the picked element may be probed for a readable list.
+ // 从被拾取元素向上最多探测多少级上级来寻找可读列表。
[DataMember(Order = 8)]
public int MaxAncestorDepth { get; set; }
/// Upper bound for a single TextPattern read so a mis-picked document cannot flood the result.
+ // 单次 TextPattern 读取的字符上限,防止误拾取整个文档时把结果撑爆。
[DataMember(Order = 9)]
public int MaxTextLength { get; set; }
}
+ // 单个单元格的读取结果。
[DataContract]
public sealed class ListCellResult
{
+ // 行号(0 基)。
[DataMember(Order = 1)]
public int RowIndex { get; set; }
+ // 列号(0 基)。
[DataMember(Order = 2)]
public int ColumnIndex { get; set; }
+ // 行标识(默认即行号字符串,Provider 提供时可为自动化 ID)。
[DataMember(Order = 3)]
public string RowId { get; set; }
+ // 列标识(默认即列号字符串)。
[DataMember(Order = 4)]
public string ColumnId { get; set; }
+ // 单元格的文本值(取不到时为 null)。
[DataMember(Order = 5)]
public string Value { get; set; }
+ // 值的来源(ValuePattern/TextPattern/Name)。
[DataMember(Order = 6)]
public ListValueSource ValueSource { get; set; }
+ // 是否取到了可用值(false 表示元素在但没暴露值)。
[DataMember(Order = 7)]
public bool ValueAvailable { get; set; }
+ // 单元格元素本身是否可用(false 表示元素缺失/GetItem 失败)。
[DataMember(Order = 8)]
public bool IsAvailable { get; set; }
+ // 读取失败时的原因说明。
[DataMember(Order = 9)]
public string Error { get; set; }
}
+ // 单行的读取结果(含其单元格列表)。
[DataContract]
public sealed class ListRowResult
{
+ // 初始化空的单元格列表。
public ListRowResult()
{
Cells = new List();
}
+ // 行号(0 基)。
[DataMember(Order = 1)]
public int RowIndex { get; set; }
+ // 行标识(默认即行号字符串)。
[DataMember(Order = 2)]
public string RowId { get; set; }
+ // 该行的所有单元格。
[DataMember(Order = 3)]
public List Cells { get; private set; }
+ // 该行是否完整(有任一单元格不可用即为 false)。
[DataMember(Order = 4)]
public bool IsComplete { get; set; }
+ // 该行的错误说明(若有)。
[DataMember(Order = 5)]
public string Error { get; set; }
}
+ // 单个选中项的结果。
[DataContract]
public sealed class ListSelectionResult
{
+ // 选中项在集合中的序号。
[DataMember(Order = 1)]
public int Index { get; set; }
+ // 选中项名称。
[DataMember(Order = 2)]
public string Name { get; set; }
+ // 选中项的 AutomationId。
[DataMember(Order = 3)]
public string AutomationId { get; set; }
+ // 该选中项信息是否成功取得。
[DataMember(Order = 4)]
public bool IsAvailable { get; set; }
+ // 读取该项失败时的原因说明。
[DataMember(Order = 5)]
public string Error { get; set; }
+ // 关联的行标识(默认取 AutomationId)。
[DataMember(Order = 6)]
public string RowId { get; set; }
}
+ // 一次列表读取的完整结果(状态、来源、行列数据、选中项、错误与提示)。
[DataContract]
public sealed class ListReadResult
{
+ // 初始化各集合;默认状态为 Unsupported、来源 Unknown、TotalRowsKnown=true。
public ListReadResult()
{
ColumnNames = new List();
@@ -172,42 +242,55 @@ namespace pacs_win_uia.Models
TotalRowsKnown = true;
}
+ // 总体状态(见 ListReadStatus)。
[DataMember(Order = 1)]
public ListReadStatus Status { get; set; }
+ // 实际采用的读取来源(见 ListReadSource)。
[DataMember(Order = 2)]
public ListReadSource Source { get; set; }
+ // 读取时间(UTC)。
[DataMember(Order = 3)]
public DateTime ReadAtUtc { get; set; }
+ // 逻辑总行数(当 TotalRowsKnown=false 时表示“当前已实现的行数”)。
[DataMember(Order = 4)]
public int RowCount { get; set; }
+ // 总列数。
[DataMember(Order = 5)]
public int ColumnCount { get; set; }
+ // 实际读到的行数。
[DataMember(Order = 6)]
public int RowsRead { get; set; }
+ // 实际读到的单元格数。
[DataMember(Order = 7)]
public int CellsRead { get; set; }
+ // 列名(缺失时以 Column0..N 占位)。
[DataMember(Order = 8)]
public List ColumnNames { get; private set; }
+ // 读取到的行及其单元格。
[DataMember(Order = 9)]
public List Rows { get; private set; }
+ // 读取到的选中项。
[DataMember(Order = 10)]
public List SelectedItems { get; private set; }
+ // 结果是否完整(有截断/不可用单元格即为 false)。
[DataMember(Order = 11)]
public bool IsComplete { get; set; }
+ // 顶层失败原因(若有)。
[DataMember(Order = 12)]
public string Error { get; set; }
+ // 错误明细(区别于 Notices,属真正的失败/异常信息)。
[DataMember(Order = 13)]
public List Errors { get; private set; }
@@ -215,20 +298,25 @@ namespace pacs_win_uia.Models
/// Non-fatal remarks such as "read through the traversal fallback". Kept separate from
/// Errors so a downgraded-but-successful read is not reported as a failure.
///
+ // 非致命提示(如“走了遍历降级”)。与 Errors 分开,避免降级但成功的结果被误报为失败。
[DataMember(Order = 14)]
public List Notices { get; private set; }
/// False when RowCount is only "rows realized right now", not a logical total.
+ // 为 false 时,RowCount 只是“当前已实现的行数”而非逻辑总数(虚拟化列表如此)。
[DataMember(Order = 15)]
public bool TotalRowsKnown { get; set; }
/// How many ancestors above the picked element produced the list; 0 = the picked element itself.
+ // 列表是在被拾取元素之上第几级找到的;0 表示就是被拾取元素自身(来自后代时为负数,见读取器)。
[DataMember(Order = 16)]
public int AncestorLevel { get; set; }
+ // 实际读取所用的元素名称。
[DataMember(Order = 17)]
public string ResolvedElementName { get; set; }
+ // 实际读取所用的元素控件类型。
[DataMember(Order = 18)]
public string ResolvedElementControlType { get; set; }
}
diff --git a/src/pacs_win_uia/Models/MsaaNodeInfo.cs b/src/pacs_win_uia/Models/MsaaNodeInfo.cs
index 5d54757..6dacc1f 100644
--- a/src/pacs_win_uia/Models/MsaaNodeInfo.cs
+++ b/src/pacs_win_uia/Models/MsaaNodeInfo.cs
@@ -3,6 +3,22 @@ using System.Runtime.Serialization;
namespace pacs_win_uia.Models
{
+ // ============================================================================
+ // MsaaNodeInfo —— 一个 MSAA(IAccessible)节点的快照。
+ //
+ // 职责:只保留原始值(名称 / 值 / 角色 / 状态 / 位置等),COM 对象读完即释放,从不长期持有。
+ //
+ // 被谁调用:MsaaService / MsaaTreeReader 产出,ControlTreeNode.Msaa 承载,拾取与属性显示消费。
+ //
+ // 字段为空意味着什么:
+ // - PathKey 是合成路径(根 HWND + 各级 child id),因为 MSAA 子节点通常没有自己的 HWND;
+ // - ChildId=0 表示对象自身,非 0 表示父对象上的简单子节点;
+ // - Name/Value 等为空 = 该属性本就为空(很多控件不提供 accValue);
+ // - Error 非空表示读取该节点时出错(个别节点失败不影响整棵树)。
+ //
+ // 要改什么就改哪里:新增 MSAA 属性 → 加字段 + Description,并同步取值键表(ControlValueKeys.Msaa)。
+ // ============================================================================
+ // MsaaNodeInfo:一个 MSAA 节点的快照;COM 对象读完即释放。
///
/// Snapshot of one MSAA (IAccessible) node. Only primitive values are kept: the COM object is
/// released as soon as the node is read, and it is never carried around.
@@ -10,6 +26,7 @@ namespace pacs_win_uia.Models
[DataContract]
public sealed class MsaaNodeInfo
{
+ // 构造:初始化位置矩形,RoleId 默认 -1(未知)。
public MsaaNodeInfo()
{
Location = new NativeRectangleInfo();
@@ -19,57 +36,71 @@ namespace pacs_win_uia.Models
/// Synthetic path (root HWND + child ids): MSAA child nodes usually have no HWND.
[DataMember(Order = 1)]
[Description("MSAA 节点的合成路径(根 HWND + 各级 child id)。MSAA 子节点通常没有自己的 HWND,所以不能按句柄标识。")]
+ // PathKey:合成路径(根 HWND + 各级 child id);MSAA 子节点无自带 HWND,只能这样标识。
public string PathKey { get; set; }
/// 0 = the object itself, otherwise the simple child id this node was read through.
[DataMember(Order = 2)]
[Description("child id:0 表示该对象自身;其它值表示这是父对象上的简单子节点(没有独立的 COM 对象)。")]
+ // ChildId:0 = 对象自身;非 0 = 父对象上的简单子节点(没有独立的 COM 对象)。
public int ChildId { get; set; }
[DataMember(Order = 3)]
[Description("MSAA 名称(accName),列表行的文本通常在这里。")]
+ // Name:MSAA 名称(accName),列表行的文本通常在这里。
public string Name { get; set; }
[DataMember(Order = 4)]
[Description("MSAA 值(accValue)。很多控件不提供该值,或与 Name 相同。")]
+ // Value:MSAA 值(accValue);很多控件不提供该值,或与 Name 相同。
public string Value { get; set; }
[DataMember(Order = 5)]
[Description("MSAA 角色 ID(ROLE_SYSTEM_*)。")]
+ // RoleId:MSAA 角色 ID(ROLE_SYSTEM_*)。
public int RoleId { get; set; }
[DataMember(Order = 6)]
[Description("MSAA 角色名称。列表/列表项/表格这类角色才可能承载列表数据。")]
+ // RoleText:MSAA 角色名称;列表 / 列表项 / 表格这类角色才可能承载列表数据。
public string RoleText { get; set; }
[DataMember(Order = 7)]
[Description("MSAA 状态位(STATE_SYSTEM_*):不可见、屏幕外、已选中、有焦点等。")]
+ // StateText:MSAA 状态位文本(STATE_SYSTEM_*:不可见 / 屏幕外 / 已选中 / 有焦点等)。
public string StateText { get; set; }
[DataMember(Order = 8)]
[Description("MSAA 描述(accDescription)。多数控件为空。")]
+ // Description:MSAA 描述(accDescription);多数控件为空。
public string Description { get; set; }
[DataMember(Order = 9)]
[Description("默认动作名称(accDefaultAction),例如“按下”。只读展示,不会触发。")]
+ // DefaultAction:默认动作名(accDefaultAction),例如“按下”;只读展示,不会触发。
public string DefaultAction { get; set; }
[DataMember(Order = 10)]
[Description("屏幕位置(accLocation)。MSAA 子节点通常只有这个矩形可用于高亮。")]
+ // Location:屏幕位置(accLocation);MSAA 子节点通常只有这个矩形可用于高亮。
public NativeRectangleInfo Location { get; set; }
[DataMember(Order = 11)]
[Description("该 MSAA 对象是否关联一个原生窗口。只有窗口型对象才有,简单子节点没有。")]
+ // HasWindow:该 MSAA 对象是否关联一个原生窗口(只有窗口型对象才有,简单子节点没有)。
public bool HasWindow { get; set; }
[DataMember(Order = 12)]
[Description("关联的原生窗口句柄(十进制);为 0 表示没有。")]
+ // WindowHandle:关联的原生窗口句柄(十进制);为 0 表示没有。
public long WindowHandle { get; set; }
[DataMember(Order = 13)]
[Description("读取该节点时的错误。个别节点失败不影响整棵树。")]
+ // Error:读取该节点时的错误;个别节点失败不影响整棵树。
public string Error { get; set; }
+ // ToString:显示为“角色: 名称(值:…)”。
public override string ToString()
{
string role = string.IsNullOrEmpty(RoleText) ? "MSAA" : RoleText;
diff --git a/src/pacs_win_uia/Models/NativeWindowInfo.cs b/src/pacs_win_uia/Models/NativeWindowInfo.cs
index df0104c..61dc39e 100644
--- a/src/pacs_win_uia/Models/NativeWindowInfo.cs
+++ b/src/pacs_win_uia/Models/NativeWindowInfo.cs
@@ -5,6 +5,25 @@ using System.Runtime.Serialization;
namespace pacs_win_uia.Models
{
+ // ============================================================================
+ // NativeWindowInfo / NativeRectangleInfo —— 原生窗口与矩形的序列化快照。
+ //
+ // 职责:
+ // - NativeWindowInfo:窗口句柄、进程、标题、类名、父子句柄、可见性 / 最小化与窗口 / 客户区矩形;
+ // - NativeRectangleInfo:一个可序列化的 LTRB 矩形(带有效性标志)。
+ //
+ // 被谁调用:NativeWindowService / Win32 读取器产出;ControlTreeNode.Window、PointPickResult、
+ // 窗口枚举与悬浮条的窗口定位消费。
+ //
+ // 字段为空意味着什么:
+ // - Handle/Hwnd 为 0(IntPtr.Zero)= 没有有效窗口;
+ // - Title/ClassName 为空 = 该窗口没有标题 / 类名;
+ // - IsValid=false 的矩形表示读不到或无效,Width/Height 记 0,转 Rectangle 得 Empty;
+ // - Error 非空表示读取该窗口信息时出错。
+ //
+ // 要改什么就改哪里:窗口字段加在 NativeWindowInfo;矩形运算在 NativeRectangleInfo。
+ // ============================================================================
+ // NativeWindowInfo:原生窗口的快照;句柄的运行期与可序列化形式分开保存。
///
/// A serializable snapshot of the native window information available through Win32.
/// The live HWND is kept separately from the serializable numeric representation.
@@ -12,6 +31,7 @@ namespace pacs_win_uia.Models
[DataContract]
public sealed class NativeWindowInfo
{
+ // 构造:由句柄初始化 Handle/Hwnd/HwndHex,并创建窗口 / 客户区两个空矩形。
public NativeWindowInfo(IntPtr handle)
{
Handle = handle;
@@ -23,57 +43,74 @@ namespace pacs_win_uia.Models
[IgnoreDataMember]
[Browsable(false)]
+ // Handle:运行期使用的 IntPtr 句柄(不序列化、不显示)。
public IntPtr Handle { get; private set; }
+ // Hwnd:句柄的十进制数值形式(可序列化)。
[DataMember(Order = 1)]
public long Hwnd { get; private set; }
+ // HwndHex:句柄的十六进制显示文本(如 0x000A1B2C)。
[DataMember(Order = 2)]
public string HwndHex { get; private set; }
+ // ProcessId:窗口所属进程 ID。
[DataMember(Order = 3)]
public int ProcessId { get; set; }
+ // ProcessName:窗口所属进程名。
[DataMember(Order = 4)]
public string ProcessName { get; set; }
+ // Title:窗口标题;跨进程读取可能变慢,可被 ControlTreeOptions 跳过。
[DataMember(Order = 5)]
public string Title { get; set; }
+ // ClassName:窗口类名。
[DataMember(Order = 6)]
public string ClassName { get; set; }
+ // ParentHwndHex:父窗口句柄(十六进制);无父窗口时为空。
[DataMember(Order = 7)]
public string ParentHwndHex { get; set; }
+ // RootHwndHex:顶层 / 根窗口句柄(十六进制)。
[DataMember(Order = 8)]
public string RootHwndHex { get; set; }
+ // IsVisible:窗口是否可见。
[DataMember(Order = 9)]
public bool IsVisible { get; set; }
+ // IsMinimized:窗口是否最小化。
[DataMember(Order = 10)]
public bool IsMinimized { get; set; }
+ // IsOwnProcess:是否属于本工具自身进程(用于排除自身窗口)。
[DataMember(Order = 11)]
public bool IsOwnProcess { get; set; }
+ // WindowBounds:窗口矩形(含边框)。
[DataMember(Order = 12)]
public NativeRectangleInfo WindowBounds { get; set; }
+ // ClientBounds:客户区矩形。
[DataMember(Order = 13)]
public NativeRectangleInfo ClientBounds { get; set; }
+ // Error:读取该窗口信息时的错误;正常为空。
[DataMember(Order = 14)]
public string Error { get; set; }
[Browsable(false)]
[IgnoreDataMember]
+ // WindowRectangle:窗口矩形转成 System.Drawing.Rectangle(不序列化)。
public Rectangle WindowRectangle
{
get { return WindowBounds == null ? Rectangle.Empty : WindowBounds.ToRectangle(); }
}
+ // ToString:显示为“标题 [进程] 句柄”。
public override string ToString()
{
string title = string.IsNullOrEmpty(Title) ? "(无标题)" : Title;
@@ -81,19 +118,23 @@ namespace pacs_win_uia.Models
return string.Format("{0} [{1}] {2}", title, process, HwndHex);
}
+ // FormatHandle:把句柄格式化为 0x 十六进制文本。
public static string FormatHandle(IntPtr handle)
{
return string.Format("0x{0:X}", handle.ToInt64());
}
}
+ // NativeRectangleInfo:可序列化的 LTRB 矩形(含 IsValid 有效性标志)。
[DataContract]
public sealed class NativeRectangleInfo
{
+ // 空构造:默认无效矩形(IsValid=false)。
public NativeRectangleInfo()
{
}
+ // 构造:按 LTRB 赋值,并据 right>=left 且 bottom>=top 判定有效性。
public NativeRectangleInfo(int left, int top, int right, int bottom)
{
Left = left;
@@ -103,26 +144,33 @@ namespace pacs_win_uia.Models
IsValid = right >= left && bottom >= top;
}
+ // Left:左边界(像素)。
[DataMember(Order = 1)]
public int Left { get; set; }
+ // Top:上边界。
[DataMember(Order = 2)]
public int Top { get; set; }
+ // Right:右边界。
[DataMember(Order = 3)]
public int Right { get; set; }
+ // Bottom:下边界。
[DataMember(Order = 4)]
public int Bottom { get; set; }
+ // IsValid:矩形是否有效;无效时宽高为 0。
[DataMember(Order = 5)]
public bool IsValid { get; set; }
+ // Width:宽度(仅有效时计算,否则 0)。
public int Width
{
get { return IsValid ? Math.Max(0, Right - Left) : 0; }
}
+ // Height:高度(仅有效时计算,否则 0)。
public int Height
{
get { return IsValid ? Math.Max(0, Bottom - Top) : 0; }
@@ -130,11 +178,13 @@ namespace pacs_win_uia.Models
[IgnoreDataMember]
[Browsable(false)]
+ // Rectangle:转成 System.Drawing.Rectangle(不序列化)。
public Rectangle Rectangle
{
get { return ToRectangle(); }
}
+ // ToRectangle:按 LTRB 生成 Rectangle;无效返回 Rectangle.Empty。
public Rectangle ToRectangle()
{
if (!IsValid)
@@ -145,6 +195,7 @@ namespace pacs_win_uia.Models
return Rectangle.FromLTRB(Left, Top, Right, Bottom);
}
+ // ToString:显示“(L,T) - (R,B) [WxH]”,无效显示“不可用”。
public override string ToString()
{
return IsValid
@@ -152,6 +203,7 @@ namespace pacs_win_uia.Models
: "不可用";
}
+ // FromRectangle:由 System.Drawing.Rectangle 生成快照;空矩形返回无效对象。
public static NativeRectangleInfo FromRectangle(Rectangle rectangle)
{
if (rectangle.IsEmpty)
diff --git a/src/pacs_win_uia/Models/PointPickResult.cs b/src/pacs_win_uia/Models/PointPickResult.cs
index 5375ba8..9671753 100644
--- a/src/pacs_win_uia/Models/PointPickResult.cs
+++ b/src/pacs_win_uia/Models/PointPickResult.cs
@@ -4,43 +4,71 @@ using System.Runtime.Serialization;
namespace pacs_win_uia.Models
{
+ // ============================================================================
+ // PointPickResult —— 一次“按点拾取”(鼠标下元素)的结果。
+ //
+ // 职责:记录拾取坐标、各来源的命中情况(窗口 / UIA 元素 / MSAA 节点 / 最深层子窗口)、
+ // 用于高亮的矩形,以及是否只拾取到窗口本身。
+ //
+ // 被谁调用:点选 / 拾取交互产出;监控编辑器与高亮显示消费。
+ //
+ // 字段为空意味着什么:
+ // - Window/AutomationElement/Msaa/DeepestWindow 为 null = 该来源没有命中;
+ // - Bounds 为空或无效 = 没有可用高亮矩形(HasBounds=false);
+ // - FailureReason 非空 = 拾取失败原因;
+ // - IsWindowOnlyPick=true = 光标下只能识别到窗口本身(如实告知,不假装窗口就是控件)。
+ //
+ // 要改什么就改哪里:新增拾取来源字段即可,其取值含义沿用各来源模型。
+ // ============================================================================
+ // PointPickResult:一次按点拾取的结果(坐标 + 各来源命中 + 高亮矩形)。
[DataContract]
public sealed class PointPickResult
{
+ // ScreenX:拾取点屏幕 X 坐标。
[DataMember(Order = 1)]
public int ScreenX { get; set; }
+ // ScreenY:拾取点屏幕 Y 坐标。
[DataMember(Order = 2)]
public int ScreenY { get; set; }
+ // Window:光标下的原生窗口;null = 没命中。
[DataMember(Order = 3)]
public NativeWindowInfo Window { get; set; }
+ // AutomationElement:光标下的 UIA 元素快照;null = UIA 没命中。
[DataMember(Order = 4)]
public UiaElementInfo AutomationElement { get; set; }
+ // IsToolWindow:命中的窗口是否属于本工具自身。
[DataMember(Order = 5)]
public bool IsToolWindow { get; set; }
+ // FailureReason:拾取失败原因;成功时为空。
[DataMember(Order = 6)]
public string FailureReason { get; set; }
+ // PickSource:实际识别到目标的来源(UIA/MSAA/Win32)。
/// Which source actually identified the picked target.
[DataMember(Order = 7)]
public ControlTreeSource PickSource { get; set; }
+ // Msaa:拾取点处的 MSAA 命中结果(当 MSAA 能识别时)。
/// MSAA hit-test result at the picked point, when MSAA could identify it.
[DataMember(Order = 8)]
public MsaaNodeInfo Msaa { get; set; }
+ // DeepestWindow:拾取点处最深的子窗口(浏览器外壳时即其渲染窗口)。
/// Deepest child window at the point (Win32 answer; the renderer window for a browser shell).
[DataMember(Order = 9)]
public NativeWindowInfo DeepestWindow { get; set; }
+ // Bounds:用于高亮的矩形(哪个来源产生就用哪个)。
/// Rectangle used for highlighting, whichever source produced it.
[DataMember(Order = 10)]
public NativeRectangleInfo Bounds { get; set; }
+ // IsWindowOnlyPick:光标下只能识别到窗口本身(如实标记,不假装窗口就是控件)。
///
/// True when nothing under the cursor could be identified beyond the window itself: the pick
/// is honest about it instead of pretending the window is the control.
@@ -48,12 +76,14 @@ namespace pacs_win_uia.Models
[DataMember(Order = 11)]
public bool IsWindowOnlyPick { get; set; }
+ // HasBounds:是否有有效的高亮矩形。
[IgnoreDataMember]
public bool HasBounds
{
get { return Bounds != null && Bounds.IsValid; }
}
+ // ScreenPoint:坐标的 Point 便捷视图(读写 ScreenX/ScreenY)。
[IgnoreDataMember]
public Point ScreenPoint
{
@@ -65,12 +95,14 @@ namespace pacs_win_uia.Models
}
}
+ // HasNativeWindow:是否命中有效原生窗口。
[IgnoreDataMember]
public bool HasNativeWindow
{
get { return Window != null && Window.Handle != IntPtr.Zero; }
}
+ // HasAutomationElement:是否命中可用的 UIA 元素。
[IgnoreDataMember]
public bool HasAutomationElement
{
diff --git a/src/pacs_win_uia/Models/UiaElementInfo.cs b/src/pacs_win_uia/Models/UiaElementInfo.cs
index fc405ef..3a18406 100644
--- a/src/pacs_win_uia/Models/UiaElementInfo.cs
+++ b/src/pacs_win_uia/Models/UiaElementInfo.cs
@@ -7,12 +7,31 @@ using System.Windows.Automation;
namespace pacs_win_uia.Models
{
+ // ============================================================================
+ // UiaElementInfo —— 一个 AutomationElement 的“安全快照”(不序列化 COM 对象本身)。
+ //
+ // 职责:把 UIA 元素读成一组可序列化 / 可绑定的字段,供控件树、属性网格、拾取与监控使用;
+ // Element 只作运行期回跳句柄,RuntimeId 按需补读。
+ //
+ // 被谁调用:UiAutomationService / UIA 读取器产出,ControlTreeNode.Uia 承载,
+ // 界面属性网格、拾取、监控编辑器与导出器消费。
+ //
+ // 字段为空意味着什么:
+ // - 字符串字段(Name/AutomationId 等)为空 = 该属性确实为空,不一定是没读到;
+ // - bool? 字段(IsEnabled/IsOffscreen/HasKeyboardFocus 等)为 null = 本次快照没有读到该属性;
+ // - IsAvailable=false 时由 Error 说明为什么读不到(如元素已销毁);
+ // - RuntimeId 默认留空,需要时调用 EnsureRuntimeId 走一次跨进程调用补上。
+ //
+ // 要改什么就改哪里:新增 UIA 属性 → 加字段 + Description,并同步取值键表(ControlValueKeys.Uia)。
+ // ============================================================================
+ // UiaElementInfo:UIA 元素的序列化快照;Element 本身不序列化。
///
/// A safe snapshot of an AutomationElement. AutomationElement itself is intentionally not serialized.
///
[DataContract]
public sealed class UiaElementInfo
{
+ // 构造:初始化模式 / 属性错误列表与矩形对象。
public UiaElementInfo()
{
SupportedPatterns = new List();
@@ -22,6 +41,7 @@ namespace pacs_win_uia.Models
[IgnoreDataMember]
[Browsable(false)]
+ // Element:运行期持有的 AutomationElement(不序列化、不显示);元素失效后访问会抛异常。
public AutomationElement Element { get; set; }
///
@@ -32,18 +52,21 @@ namespace pacs_win_uia.Models
[Browsable(true)]
[ReadOnly(true)]
[Description("从顶层窗口到该控件的 UIA 路径(与监控列表保存的路径同格式,可粘进「杂项 → 按 path 定位」验证)。")]
+ // ControlPath:显示用——从顶层窗口到该控件的 UIA 路径(与监控保存同格式,可粘去「按 path 定位」验证),不序列化。
public string ControlPath { get; set; }
[IgnoreDataMember]
[Browsable(true)]
[ReadOnly(true)]
[Description("页面特征:进程=…;标题关键词=…;窗口类=…(与悬浮条显示条件同一套取值)。")]
+ // PageFeatures:显示用页面特征文本(进程/标题关键词/窗口类),不序列化。
public string PageFeatures { get; set; }
[IgnoreDataMember]
[Browsable(true)]
[ReadOnly(true)]
[Description("该控件当前是否获得键盘焦点(未知 = 本次快照没有读焦点)。")]
+ // FocusState:当前键盘焦点状态(有/无/未知),不序列化。
public string FocusState
{
get { return HasKeyboardFocus.HasValue ? (HasKeyboardFocus.Value ? "是" : "否") : "未知"; }
@@ -51,67 +74,83 @@ namespace pacs_win_uia.Models
[DataMember(Order = 1)]
[Description("UIA 名称。按钮文字、列表行的文本通常在这里;为空不代表控件没有内容,可能要从 ValuePattern/TextPattern 取。")]
+ // Name:UIA 名称;为空不代表没有内容(可能要从 ValuePattern/TextPattern 取)。
public string Name { get; set; }
[DataMember(Order = 2)]
[Description("控件在程序内部的 AutomationId。通常比 Name 稳定,适合用来定位要监控的控件。")]
+ // AutomationId:程序内部标识;通常比 Name 稳定,适合用来定位要监控的控件。
public string AutomationId { get; set; }
[DataMember(Order = 3)]
[Description("UIA 控件类型,决定这个控件支持哪些模式(Pattern)。列表必须是 List/DataGrid/Table/Tree 这类容器类型。")]
+ // ControlType:UIA 控件类型,决定该控件支持哪些 Pattern。
public string ControlType { get; set; }
[DataMember(Order = 4)]
[Description("Win32 窗口类名。Chrome_WidgetWin_1 = Chromium/CEF 内核;WindowsForms10.* = WinForms;HwndWrapper* = WPF。")]
+ // ClassName:Win32 窗口类名(可据此判断内核:Chrome_WidgetWin_1=CEF,WindowsForms10.*=WinForms,HwndWrapper*=WPF)。
public string ClassName { get; set; }
[DataMember(Order = 5)]
[Description("无障碍提供者框架:Win32 / WinForm / WPF / UIA。框架不同,能读到的信息差别很大。")]
+ // FrameworkId:无障碍提供者框架(Win32/WinForm/WPF/UIA);框架不同,能读到的信息差别很大。
public string FrameworkId { get; set; }
[DataMember(Order = 6)]
[Description("原生窗口句柄(十进制)。为 0 表示这是一个没有独立窗口的元素(自绘/无窗口控件)。")]
+ // NativeWindowHandle:原生窗口句柄(十进制);0 表示这是一个没有独立窗口的元素。
public long NativeWindowHandle { get; set; }
[DataMember(Order = 7)]
[Description("控件当前是否可用(未禁用)。")]
+ // IsEnabled:控件是否可用(未禁用);null = 本次快照没读到。
public bool? IsEnabled { get; set; }
[DataMember(Order = 8)]
[Description("控件是否在屏幕外:被滚动出可视区域、已折叠或已隐藏。遍历降级读取时这些行读不到。")]
+ // IsOffscreen:是否在屏幕外(滚动出可视区/折叠/隐藏);null = 没读到。
public bool? IsOffscreen { get; set; }
[DataMember(Order = 9)]
[Description("控件在屏幕上的矩形(像素)。高亮框和拾取定位都用它。")]
+ // BoundingRectangle:控件在屏幕上的矩形(像素),用于高亮框与拾取定位。
public NativeRectangleInfo BoundingRectangle { get; set; }
[DataMember(Order = 10)]
[Description("所属进程 ID。跨进程读取可能变慢或卡住;权限较低时也读不到更高权限的进程。")]
+ // ProcessId:所属进程 ID(跨进程读取可能变慢或受权限限制)。
public int ProcessId { get; set; }
[DataMember(Order = 11)]
+ // ProviderDescription:UIA 提供者描述(诊断用)。
public string ProviderDescription { get; set; }
[DataMember(Order = 12)]
[Description("本次快照是否成功读到了这个元素。为 False 时下面的 Error 会说明原因。")]
+ // IsAvailable:本次快照是否成功读到该元素;为 false 时看 Error。
public bool IsAvailable { get; set; }
[DataMember(Order = 13)]
[Description("读取失败的原因。ElementNotAvailable 通常表示控件已经销毁或被重建。")]
+ // Error:读取失败原因(ElementNotAvailable 表示控件已销毁或被重建)。
public string Error { get; set; }
[DataMember(Order = 14)]
[Description("该元素支持的 UIA 模式列表。读取列表依赖 GridPattern/TablePattern/SelectionPattern;没有这些模式时会走子元素遍历降级。")]
+ // SupportedPatterns:支持的模式列表;读取列表依赖 Grid/Table/Selection 模式,没有则走子元素遍历降级。
public List SupportedPatterns { get; private set; }
[DataMember(Order = 15)]
[Description("UIA RuntimeId。同一进程内可用来重新绑定元素,但程序重启后会变化,只能当线索,不能当稳定标识。(树快照里按需填充:它要走一次跨进程调用,逐节点读取会明显拖慢控件树。)")]
+ // RuntimeId:UIA RuntimeId(按需填充:每个节点一次跨进程调用,逐节点读取会明显拖慢树)。
public string RuntimeId { get; set; }
///
/// Fills RuntimeId on demand. Reading it for every tree node costs one cross-process call per
/// node, which is why snapshots leave it empty until something actually needs it.
///
+ // EnsureRuntimeId:按需填充 RuntimeId(每个节点一次跨进程调用,故快照默认留空);失败记入 PropertyErrors。
public void EnsureRuntimeId()
{
if (!string.IsNullOrEmpty(RuntimeId) || Element == null)
@@ -135,23 +174,28 @@ namespace pacs_win_uia.Models
[DataMember(Order = 16)]
[Description("逐个属性读取失败的记录(某个 Provider 拒绝某个属性时不会让整个快照失败)。")]
+ // PropertyErrors:逐个属性读取失败的记录(某个 Provider 拒绝某属性时不会让整份快照失败)。
public List PropertyErrors { get; private set; }
[DataMember(Order = 17)]
[Description("该控件当前是否有键盘焦点(UIA HasKeyboardFocus)。用于监控“现在焦点在哪个控件”,与“是否被选中”不是一回事。")]
+ // HasKeyboardFocus:当前是否有键盘焦点(与“是否被选中”不是一回事);null = 没读到。
public bool? HasKeyboardFocus { get; set; }
[DataMember(Order = 18)]
[Description("该控件是否可以获得键盘焦点(UIA IsKeyboardFocusable)。不能获得焦点的控件,焦点状态永远是“否”。")]
+ // IsKeyboardFocusable:是否可获得键盘焦点;不能获得焦点的控件,焦点状态永远是“否”。
public bool? IsKeyboardFocusable { get; set; }
[Browsable(false)]
[IgnoreDataMember]
+ // BoundingRectangleValue:把快照矩形转成 System.Drawing.Rectangle(不序列化),方便绘制。
public Rectangle BoundingRectangleValue
{
get { return BoundingRectangle == null ? Rectangle.Empty : BoundingRectangle.ToRectangle(); }
}
+ // ToString:显示为“控件类型: 名称”。
public override string ToString()
{
string type = string.IsNullOrEmpty(ControlType) ? "未知控件" : ControlType;
@@ -160,23 +204,29 @@ namespace pacs_win_uia.Models
}
}
+ // UiaTreeNodeInfo:UIA 元素的旧树节点(元素 + 子节点)。
[DataContract]
public sealed class UiaTreeNodeInfo
{
+ // 构造:初始化空子节点列表。
public UiaTreeNodeInfo()
{
Children = new List();
}
+ // Element:该节点承载的 UIA 元素快照。
[DataMember(Order = 1)]
public UiaElementInfo Element { get; set; }
+ // Children:子节点列表(顺序即树顺序)。
[DataMember(Order = 2)]
public List Children { get; private set; }
+ // ChildrenComplete:该节点的子节点是否读取完整。
[DataMember(Order = 3)]
public bool ChildrenComplete { get; set; }
+ // ChildrenError:子节点读取不完整时的原因。
[DataMember(Order = 4)]
public string ChildrenError { get; set; }
}
diff --git a/src/pacs_win_uia/Models/WindowEnumerationResult.cs b/src/pacs_win_uia/Models/WindowEnumerationResult.cs
index 3d793f1..6518429 100644
--- a/src/pacs_win_uia/Models/WindowEnumerationResult.cs
+++ b/src/pacs_win_uia/Models/WindowEnumerationResult.cs
@@ -3,20 +3,38 @@ using System.Runtime.Serialization;
namespace pacs_win_uia.Models
{
+ // ============================================================================
+ // WindowEnumerationResult —— 一次顶层窗口枚举的结果。
+ //
+ // 职责:携带枚举是否成功、错误信息与窗口列表。
+ //
+ // 被谁调用:NativeWindowService.EnumerateTopLevelWindows 产出;窗口列表与监控的窗口定位消费。
+ //
+ // 字段为空意味着什么:
+ // - Succeeded=false 时看 Error;此时 Windows 仍可能是部分结果;
+ // - Error 非空表示枚举出错。
+ //
+ // 要改什么就改哪里:这里只是枚举结果字段;真正的枚举逻辑在 NativeWindowService。
+ // ============================================================================
+ // WindowEnumerationResult:顶层窗口枚举的结果(成功标志 + 错误 + 窗口列表)。
[DataContract]
public sealed class WindowEnumerationResult
{
+ // 构造:初始化空窗口列表。
public WindowEnumerationResult()
{
Windows = new List();
}
+ // Succeeded:枚举是否成功。
[DataMember(Order = 1)]
public bool Succeeded { get; set; }
+ // Error:枚举出错时的原因;成功为空。
[DataMember(Order = 2)]
public string Error { get; set; }
+ // Windows:枚举到的顶层窗口列表。
[DataMember(Order = 3)]
public List Windows { get; private set; }
}
diff --git a/src/pacs_win_uia/Picker/CrosshairPicker.cs b/src/pacs_win_uia/Picker/CrosshairPicker.cs
index 7d052e9..dba0608 100644
--- a/src/pacs_win_uia/Picker/CrosshairPicker.cs
+++ b/src/pacs_win_uia/Picker/CrosshairPicker.cs
@@ -9,6 +9,24 @@ using pacs_win_uia.Models;
using pacs_win_uia.Services;
using pacs_win_uia.UI;
+// ============================================================================
+// CrosshairPicker.cs —— 十字拾取器:协调覆盖层、目标探测与高亮
+// 职责:非侵入式地让用户移动鼠标选取目标控件:显示十字覆盖层 → 探测光标下目标 → 预览高亮 → 点击确认。
+// 低级鼠标钩子吞左键的原因:覆盖层是故意点击穿透的(工具必须看到光标下的窗口),若不吞左键,
+// 每次拾取都会顺带按下被拾取的控件(按钮、菜单上立刻可见),所以拾取期间用 WH_MOUSE_LL 接管左键。
+// 点击 1.2 秒硬期限与 Win32 兜底:点击后若 UIA 探测在 1.2 秒内没回来,看门狗用 ProbeWindowOnly
+// 按 Win32 窗口信息确认目标,绝不让覆盖层一直挂着。
+// 探测单飞与看门狗:同一时刻只跑一个探测,未完成时新坐标记作 pending;单次探测超过 2 秒视为卡住,
+// 放弃并允许下次鼠标移动重试(但待确认的点击保留自己的期限,不在这里丢弃)。
+// Esc 取消:覆盖层检测到 Esc 触发 Cancel → 停止并抛出 Canceled 事件。
+// 覆盖层点击穿透:PickerOverlayForm 用 WS_EX_TRANSPARENT/NOACTIVATE + HTCLIENT 等实现穿透与不抢焦点。
+// 被谁调用:主窗口/工具条在用户点“拾取”时创建并 Start。
+// 要改什么就改哪里:
+// - 时限常量:PickWaitTimeout(1.2s)、ProbeStuckThreshold(2s)、看门狗间隔。
+// - 探测调度/单飞:StartProbe、CompletePreview、ProbeWatchdogOnTick。
+// - 点击接管:InstallMouseHook、MouseHookCallback、ConfirmPickAt。
+// - 收尾/取消:FinishPick、Stop、Cancel。
+// ============================================================================
namespace pacs_win_uia.Picker
{
///
@@ -16,33 +34,59 @@ namespace pacs_win_uia.Picker
///
public sealed class CrosshairPicker : IDisposable
{
+ // 单次探测卡住阈值:超过 2 秒视为提供者无响应。
private static readonly TimeSpan ProbeStuckThreshold = TimeSpan.FromSeconds(2);
+ // 点击确认后等待探测结果的硬期限:1.2 秒。
private static readonly TimeSpan PickWaitTimeout = TimeSpan.FromSeconds(1.2);
+ // 宿主控件(用于把钩子回调派发回 UI 线程)。
private readonly Control _owner;
+ // 本工具自身进程 ID。
private readonly int _ownProcessId;
+ // 目标探测服务。
private readonly TargetProbeService _probeService;
+ // 预览高亮跟随器。
private readonly HighlightFollower _highlight;
+ // 探测看门狗定时器(检查卡住与点击期限)。
private readonly System.Windows.Forms.Timer _probeWatchdog;
+ // 全屏十字覆盖层窗体。
private PickerOverlayForm _pickerOverlay;
+ // 本次拾取的取消源。
private CancellationTokenSource _operationCancellation;
+ // 是否正在拾取。
private bool _isPicking;
+ // 探测序号(用于丢弃过期的探测结果)。
private int _probeSequence;
+ // 上一次已发起探测的坐标。
private Point _lastProbePoint;
+ // 是否已有 _lastProbePoint。
private bool _hasLastProbePoint;
+ // 光标下最近一次解析到的原生窗口句柄。
private IntPtr _lastNativeWindowHandle;
+ // 探测进行中时暂存的待探测坐标。
private Point _pendingProbePoint;
+ // 是否有待探测坐标。
private bool _hasPendingProbePoint;
+ // 本次点击确认的坐标。
private Point _pickPoint;
+ // 是否已请求确认点击。
private bool _pickRequested;
+ // 最近一次探测结果。
private PointPickResult _lastResult;
+ // 当前在跑的探测任务(单飞)。
private Task _probeTask;
/// Keeps the confirmation click away from the target application.
+ /// 低级鼠标钩子回调委托(需保持引用防止被 GC)。
private NativeMethods.LowLevelMouseProc _mouseHook;
+ // 钩子句柄。
private IntPtr _mouseHookHandle = IntPtr.Zero;
+ // 左键是否已由本工具接管(吞掉)。
private bool _pendingClickSwallowed;
+ // 本次探测的发起时间(用于卡住判定)。
private DateTime _probeStartedUtc;
+ // 点击确认的截止时间(用于硬期限兜底)。
private DateTime _pickDeadlineUtc;
+ // 构造:注入宿主与探测服务,建高亮跟随器,并把看门狗定时器调到 150ms 以便够细地守住 1.2s 期限。
public CrosshairPicker(Control owner, TargetProbeService probeService)
{
_owner = owner ?? throw new ArgumentNullException("owner");
@@ -58,15 +102,20 @@ namespace pacs_win_uia.Picker
_probeWatchdog.Tick += ProbeWatchdogOnTick;
}
+ // 是否正在拾取(只读)。
public bool IsPicking
{
get { return _isPicking; }
}
+ // 预览结果变化(鼠标移动导致高亮/目标变化)。
public event EventHandler PreviewChanged;
+ // 成功确认拾取(带上最终结果)。
public event EventHandler Picked;
+ // 拾取被取消(Esc)。
public event EventHandler Canceled;
+ // 开始拾取:复位状态、创建并显示覆盖层、启动看门狗、安装鼠标钩子。
public void Start()
{
if (_isPicking || _owner.IsDisposed)
@@ -98,6 +147,8 @@ namespace pacs_win_uia.Picker
/// Two jobs: a confirmed click must always end the pick (even when the provider never
/// answers), and a wedged preview probe must not disable preview for the rest of the session.
///
+ /// 看门狗:① 已点击但超过 1.2s 硬期限 → 用 Win32 兜底确认,绝不让覆盖层挂着;
+ /// ② 预览探测卡住超过 2s → 放弃本次并在下次移动时重试(但保留待确认点击的期限)。
private void ProbeWatchdogOnTick(object sender, EventArgs e)
{
if (!_isPicking)
@@ -137,6 +188,7 @@ namespace pacs_win_uia.Picker
}
}
+ // 取消本次拾取:停止并抛出 Canceled(幂等,未在拾取时直接返回)。
public void Cancel()
{
if (!_isPicking)
@@ -153,6 +205,7 @@ namespace pacs_win_uia.Picker
}
}
+ // 覆盖层光标移动:坐标未变跳过;有探测在跑就记 pending 单飞,否则立即发起探测。
private void PickerOverlayOnCursorMoved(object sender, CursorPositionEventArgs e)
{
if (!_isPicking || _operationCancellation == null)
@@ -179,6 +232,7 @@ namespace pacs_win_uia.Picker
StartProbe(screenPoint);
}
+ // 发起一次异步探测(自增序号,完成回调回到 UI 线程)。
private void StartProbe(Point screenPoint)
{
if (!_isPicking || _operationCancellation == null)
@@ -197,6 +251,7 @@ namespace pacs_win_uia.Picker
TaskScheduler.FromCurrentSynchronizationContext());
}
+ // 探测完成回调:丢弃过期结果、按结果更新高亮、处理待确认点击与 pending 坐标。
private void CompletePreview(int sequence, Point probedPoint, Task task)
{
if (!_isPicking || sequence != _probeSequence)
@@ -268,11 +323,13 @@ namespace pacs_win_uia.Picker
}
}
+ // 覆盖层按下 Esc → 取消拾取。
private void PickerOverlayOnEscapePressed(object sender, EventArgs e)
{
Cancel();
}
+ // 覆盖层收到左键释放 → 在当前位置确认拾取。
private void PickerOverlayOnLeftButtonReleased(object sender, EventArgs e)
{
ConfirmPickAt(Cursor.Position);
@@ -284,6 +341,7 @@ namespace pacs_win_uia.Picker
/// without the hook every pick would also press the control being picked — which an operator
/// notices immediately on a button or a menu.
///
+ /// 安装低级鼠标钩子接管左键:覆盖层是点击穿透的,不吞左键就会顺带按下被拾取的控件。
private void InstallMouseHook()
{
if (_mouseHookHandle != IntPtr.Zero || !_isPicking)
@@ -306,6 +364,7 @@ namespace pacs_win_uia.Picker
AppLog.Info("拾取期间左键由本工具接管:不会传给目标窗口,也不会抢焦点。");
}
+ // 卸载鼠标钩子(幂等),清除句柄与委托引用。
private void UninstallMouseHook()
{
if (_mouseHookHandle == IntPtr.Zero)
@@ -327,11 +386,13 @@ namespace pacs_win_uia.Picker
}
/// True when the pick click is taken by the tool instead of the target application.
+ /// 拾取点击是否由本工具吞掉(而不是传给目标应用)。
public bool ClicksAreSwallowed
{
get { return _pendingClickSwallowed; }
}
+ // 鼠标钩子回调:只处理左键按下/抬起,抬起时把确认派发到 UI 队列并吞掉该消息(返回 1)。
private IntPtr MouseHookCallback(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0 || !_isPicking)
@@ -369,6 +430,7 @@ namespace pacs_win_uia.Picker
}
/// Confirms a pick at an explicit point (the hook's coordinates, or the overlay's).
+ /// 在指定点确认拾取:刷新光标下句柄、设置点击期限、必要时立即发起一次探测。
private void ConfirmPickAt(Point screenPoint)
{
if (!_isPicking)
@@ -394,6 +456,7 @@ namespace pacs_win_uia.Picker
}
}
+ // 正常收尾:无效目标允许重试(保持拾取器开着)。
private void FinishPick(PointPickResult result)
{
FinishPick(result, true);
@@ -403,6 +466,7 @@ namespace pacs_win_uia.Picker
/// True for a normal probe result: clicking an unusable spot keeps the picker up so the user
/// can aim again. False for the deadline fallback, where the click must end the session.
///
+ /// 收尾:结果无效时按 allowRetryWhenInvalid 决定重试还是结束;有效则停止并抛 Picked。
private void FinishPick(PointPickResult result, bool allowRetryWhenInvalid)
{
if (result == null || result.IsToolWindow || !result.HasNativeWindow)
@@ -445,6 +509,7 @@ namespace pacs_win_uia.Picker
}
}
+ // 覆盖层被关闭(用户直接关窗)→ 安全停止。
private void PickerOverlayOnFormClosed(object sender, FormClosedEventArgs e)
{
if (_isPicking)
@@ -453,6 +518,7 @@ namespace pacs_win_uia.Picker
}
}
+ // 停止拾取:停看门狗、卸钩子、作废在跑的探测、关闭并释放覆盖层、隐藏高亮。
private void Stop()
{
_isPicking = false;
@@ -483,6 +549,7 @@ namespace pacs_win_uia.Picker
_highlight.Hide("拾取结束。");
}
+ // 释放:停止拾取、卸载钩子、解绑并释放看门狗与高亮跟随器。
public void Dispose()
{
Stop();
diff --git a/src/pacs_win_uia/Program.cs b/src/pacs_win_uia/Program.cs
index dcfd843..dbe3ac3 100644
--- a/src/pacs_win_uia/Program.cs
+++ b/src/pacs_win_uia/Program.cs
@@ -1,3 +1,37 @@
+// =============================================================================
+// Program.cs —— 进程入口、命令行解析与单实例转发
+//
+// 职责:
+// 本工具唯一入口。解析命令行,决定本次是「打开 GUI(默认)」还是「无界面读取」,
+// 并负责单实例:已有实例在运行时把本次请求转发给它,绝不在本地另起一个实例。
+//
+// 被谁调用:
+// 操作系统(CLR)调用 Main;Main 内部使用 SingleInstanceService(单实例/转发)、
+// RunHeadless(无界面读取)、MainForm(主界面)与本文件的辅助方法。
+//
+// 启动分支:
+// 无参数 -> 打开主窗口(GUI,默认)。
+// --read-saved -> 无界面读取界面保存的配置,结果写到 exe 目录的 out.json。
+// --read-config -> 无界面读取指定配置文件并输出 JSON。
+// --help -> 打印用法。
+//
+// 单实例转发流程:
+// 先 new SingleInstanceService();拿不到互斥锁(IsOwner=false)就把请求 Forward 给
+// 已有实例,并把对方回传的 stdout/stderr/退出码当作本次结果直接返回。
+//
+// 退出码约定:
+// 0 = 全部命中;1 = 有未命中或取不到值;2 = 参数/配置错误(含启动或转发失败)。
+//
+// 为什么 headless 用传入的 writer 参数而不是重定向全局 Console:
+// 转发请求必须原样保留「调用方」的标准流。若这里调用 Console.SetOut/SetError,
+// 会连 owner 自己的控制台和其它线程的输出一起被劫持。因此所有无界面路径都只通过
+// 形参 stdout/stderr 写,绝不改动全局 Console。
+//
+// 要改什么就改哪里:
+// 增删参数/用法文案 -> Usage 常量 + RunHeadless 的 switch。
+// 退出码规则 -> Main、RunHeadless 末尾、UsageError。
+// 启动与单实例逻辑 -> Main、ExecuteRequest。
+// =============================================================================
using System;
using System.IO;
using System.Runtime.Serialization.Json;
@@ -11,8 +45,10 @@ using pacs_win_uia.Services;
namespace pacs_win_uia
{
+ // 静态入口类:只放 Main 以及命令行/单实例相关的辅助方法,不持有实例状态。
internal static class Program
{
+ // 命令行用法文本:--help 与参数错误时打印;退出码 0/1/2 的含义也写在这里。
private const string Usage =
"用法:\r\n" +
" pacs_win_uia.exe 打开界面(默认)\r\n" +
@@ -33,6 +69,7 @@ namespace pacs_win_uia
"\r\n" +
"退出码: 0=全部命中;1=有未命中或取不到值;2=参数或配置错误";
+ // 进程入口(返回值即进程退出码,约定见 Usage)。STAThread 是 WinForms/UIA 的要求。
[STAThread]
private static int Main(string[] args)
{
@@ -41,6 +78,7 @@ namespace pacs_win_uia
using (var instance = new SingleInstanceService())
{
SingleInstanceService.Request request = CreateRequest(args ?? new string[0]);
+ // 已有实例在运行:转发请求,并用对方回传的输出/退出码作为本次结果,绝不本地另起实例。
if (!instance.IsOwner)
{
SingleInstanceService.Response response = instance.Forward(request);
@@ -53,6 +91,7 @@ namespace pacs_win_uia
// Initialize diagnostics only in the owner. A forwarded request must retain the
// caller's standard streams; request capture never calls Console.SetOut/SetError.
AppLog.Init();
+ // 有参数 = 一次性无界面读取(此时 owner 也监听管道,但没有窗口)。
if (request.Arguments.Length > 0)
{
// A one-shot owner also accepts clients for its lifetime, but has no window.
@@ -66,6 +105,7 @@ namespace pacs_win_uia
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
+ // 默认分支:打开主窗口。先建好句柄,工作线程才能安全地 BeginInvoke。
using (var form = new MainForm())
{
// Create the handle on the UI thread before workers may BeginInvoke.
@@ -89,6 +129,8 @@ namespace pacs_win_uia
}
}
+ // 把命令行整理成可跨进程传递的 Request。
+ // 关键:在「启动方」进程里就把相对路径解析成绝对路径,避免改变 owner 的当前目录。
private static SingleInstanceService.Request CreateRequest(string[] args)
{
var normalized = (string[])args.Clone();
@@ -119,6 +161,8 @@ namespace pacs_win_uia
};
}
+ // owner 收到请求后的统一执行入口:既处理无界面读取,也处理「激活已有窗口」。
+ // form 为 null 表示当前 owner 是一次性无界面实例,没有窗口可激活。
private static int ExecuteRequest(SingleInstanceService.Request request, TextWriter stdout,
TextWriter stderr, CancellationToken cancellation, Form form)
{
@@ -173,6 +217,8 @@ namespace pacs_win_uia
}
}
+ // 无界面读取主流程:解析参数、加载配置、读取控件树、序列化并输出报告。
+ // 返回值:0=全部命中,1=有未命中,2=参数/配置错误。
private static int RunHeadless(string[] args, TextWriter stdout, TextWriter stderr,
string defaultOutputPath, CancellationToken cancellationToken)
{
@@ -339,6 +385,7 @@ namespace pacs_win_uia
return allRead ? 0 : 1;
}
+ // 默认配置文件路径:界面「保存」写到的位置(%LocalAppData%\pacs_win_uia\control-monitors.json)。
/// The config the GUI writes to by default.
private static string GetDefaultConfigPath()
{
@@ -346,6 +393,7 @@ namespace pacs_win_uia
return Path.Combine(directory, "pacs_win_uia", "control-monitors.json");
}
+ // 默认输出路径:exe 同目录的 out.json(从 bin\Debug 运行就写到 bin\Debug)。
/// out.json next to the executable, so running from bin\\Debug writes there.
private static string GetDefaultOutputPath()
{
@@ -355,6 +403,7 @@ namespace pacs_win_uia
"out.json");
}
+ // 把读取报告序列化为 JSON(UTF-8 无 BOM,DataContractJsonSerializer)。
private static string SerializeReport(HeadlessReport report)
{
var serializer = new DataContractJsonSerializer(typeof(HeadlessReport));
@@ -371,6 +420,7 @@ namespace pacs_win_uia
}
}
+ // 参数错误统一出口:打印消息 + 用法,记录日志,并返回退出码 2。
private static int UsageError(TextWriter stderr, string message)
{
stderr.WriteLine(message);
@@ -380,11 +430,13 @@ namespace pacs_win_uia
return 2;
}
+ // 界面线程未处理异常(Application.ThreadException);只记日志,不让界面崩溃。
private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
{
AppLog.Error("界面线程未处理异常。", e.Exception);
}
+ // 非界面线程的未处理异常(AppDomain.UnhandledException);记录后进程通常仍会终止。
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
AppLog.Error(
diff --git a/src/pacs_win_uia/Services/AccessibilityActivationService.cs b/src/pacs_win_uia/Services/AccessibilityActivationService.cs
index d6d8045..10266e3 100644
--- a/src/pacs_win_uia/Services/AccessibilityActivationService.cs
+++ b/src/pacs_win_uia/Services/AccessibilityActivationService.cs
@@ -3,6 +3,17 @@ using System.Threading;
using System.Windows.Automation;
using pacs_win_uia.Diagnostics;
+// ============================================================================
+// AccessibilityActivationService.cs —— 实验性:请求目标应用打开无障碍支持
+// 职责:用两种触发手段促使目标(Chromium/CEF/Electron/WebView2)构建无障碍树:
+// 1) 对窗口发起 MSAA 查询(WM_GETOBJECT with OBJID_CLIENT);
+// 2) 注册一个 UIA 事件处理器,使 UiaClientsAreListening() 为真。
+// 被谁调用:HeadlessConfigReader 在 activate=true 时创建,读取每条前调用 Activate。
+// 限制与已知问题:会在目标应用内部改变状态,与具体实现相关,不保证有效;必须让监听线程一直存活
+// 才能保持“有客户端在听”的标志位为真(所以单独起一个长期存活的 MTA 线程)。回调故意留空——
+// 在回调线程里再进 UIA 可能死锁,注册全局结构变更又会让应用被事件淹没。
+// 要改什么就改哪里:触发手段在 Activate;监听线程生命周期在 StartListening/StopListening/ListenLoop。
+// ============================================================================
namespace pacs_win_uia.Services
{
///
@@ -17,18 +28,25 @@ namespace pacs_win_uia.Services
///
public sealed class AccessibilityActivationService : IDisposable
{
+ // 保护监听线程启停的锁。
private readonly object _sync = new object();
+ // 用于发起 MSAA 查询的服务。
private readonly MsaaService _msaa = new MsaaService();
+ // 注册的 UIA 焦点变更处理器(保持它活着,标志位才为真)。
private AutomationFocusChangedEventHandler _handler;
+ // 长期存活的监听线程。
private Thread _listenerThread;
+ // 是否正在监听(volatile 以便跨线程可见)。
private volatile bool _listening;
+ // 当前是否在监听 UIA 事件。
public bool IsListening
{
get { return _listening; }
}
/// Turns on both triggers and describes what was done, for the status line and log.
+ /// 打开两种触发手段并返回一句中文描述(供状态栏与日志用)。
public string Activate(IntPtr handle)
{
var parts = new System.Collections.Generic.List();
@@ -73,6 +91,7 @@ namespace pacs_win_uia.Services
/// long-lived MTA thread. The callback is deliberately empty: re-entering UIA from the
/// callback thread can deadlock, and a global structure-changed handler would flood the app.
///
+ /// 启动监听线程(幂等):注册要一直存活才能保持标志位,所以放在独立的长期 MTA 线程上。
public void StartListening()
{
lock (_sync)
@@ -93,6 +112,7 @@ namespace pacs_win_uia.Services
}
}
+ // 停止监听并等待线程退出(最多 2 秒)。
public void StopListening()
{
Thread thread;
@@ -121,6 +141,7 @@ namespace pacs_win_uia.Services
}
}
+ // 监听线程主体:注册焦点事件处理器 → 循环挂住直到 _listening 变假 → 注销处理器。
private void ListenLoop()
{
try
@@ -162,12 +183,14 @@ namespace pacs_win_uia.Services
}
}
+ // 焦点变更回调:故意留空——只为让本进程被算作“正在监听的 UIA 客户端”,绝不做实际工作、绝不回调 UIA。
private static void OnFocusChanged(object sender, AutomationFocusChangedEventArgs e)
{
// Intentionally empty. This handler exists only so that the process counts as a
// listening UIA client; it must never do work, and never call back into UIA.
}
+ // 释放:停止监听(幂等)。
public void Dispose()
{
StopListening();
diff --git a/src/pacs_win_uia/Services/AppSettingsStore.cs b/src/pacs_win_uia/Services/AppSettingsStore.cs
index 2740fb4..c3dad98 100644
--- a/src/pacs_win_uia/Services/AppSettingsStore.cs
+++ b/src/pacs_win_uia/Services/AppSettingsStore.cs
@@ -1,3 +1,24 @@
+// =============================================================================
+// AppSettingsStore.cs —— 读写 settings.json(优先 exe 同目录,失败回退到用户目录)
+//
+// 职责:
+// 从 exe 同目录读取/写入 settings.json;exe 目录不可写时回退到
+// %LocalAppData%\pacs_win_uia\settings.json。文件是普通文本(非嵌入资源),可手改随包分发。
+//
+// 被谁调用:
+// Program.RunHeadless 与界面/命令相关代码通过 new AppSettingsStore().Load() 使用。
+//
+// 边界条件 / 策略:
+// - 文件不存在:生成默认设置并写回。
+// - 文件损坏/超 256 KB:记录日志,改用默认设置(原文件保留不动),保证工具仍能启动。
+// - 优先路径不存在但回退路径存在:用回退路径(说明上次只能写用户目录)。
+// - 保存时先试 exe 目录,失败再试用户目录,两者都失败则记错误并返回 false。
+//
+// 要改什么就改哪里:
+// 文件名 -> FileName 常量。
+// 大小上限 -> MaxFileBytes。
+// 路径策略 -> 构造函数、GetExeDirectoryPath / GetUserDirectoryPath、Load / Save。
+// =============================================================================
using System;
using System.IO;
using System.Runtime.Serialization.Json;
@@ -8,6 +29,7 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // 设置文件存储:优先 exe 同目录,exe 目录不可写时回退到用户目录。
///
/// Reads and writes settings.json next to the executable. It is a plain file in the output
/// folder (never an embedded resource), so it can be edited by hand and shipped with the build.
@@ -16,19 +38,26 @@ namespace pacs_win_uia.Services
///
public sealed class AppSettingsStore
{
+ // 设置文件名。
public const string FileName = "settings.json";
+ // 设置文件大小上限(256 KB),超过视为异常。
private const int MaxFileBytes = 256 * 1024;
+ // 首选路径(exe 同目录)。
private readonly string _preferredPath;
+ // 回退路径(用户目录)。
private readonly string _fallbackPath;
+ // 当前实际使用的路径(读/写都记录在此,含走回退的情况)。
private string _activePath;
+ // 默认构造:exe 同目录为首选,用户目录为回退。
public AppSettingsStore()
: this(GetExeDirectoryPath(), GetUserDirectoryPath())
{
}
+ // 指定首选/回退路径的构造(便于测试或自定义)。
public AppSettingsStore(string preferredPath, string fallbackPath)
{
_preferredPath = preferredPath ?? throw new ArgumentNullException("preferredPath");
@@ -36,22 +65,26 @@ namespace pacs_win_uia.Services
_activePath = _preferredPath;
}
+ // 实际读写所在的文件路径(可能为首选,也可能为回退)。
/// Where the settings were actually read from / written to.
public string FilePath
{
get { return _activePath; }
}
+ // 首选路径(exe 同目录)。
public string PreferredPath
{
get { return _preferredPath; }
}
+ // 回退路径(用户目录)。
public string FallbackPath
{
get { return _fallbackPath; }
}
+ // 加载设置:文件缺失则生成默认并写回;文件损坏则记日志、改用默认(原文件保留)后仍能启动。
///
/// Loads the settings; a missing file is created with defaults, and a broken file is reported
/// and replaced by defaults so the tool still starts.
@@ -97,6 +130,7 @@ namespace pacs_win_uia.Services
return settings;
}
+ // 保存设置:序列化后先写首选路径,失败再写回退路径;都失败返回 false。
public bool Save(AppSettings settings)
{
if (settings == null)
@@ -135,6 +169,7 @@ namespace pacs_win_uia.Services
return false;
}
+ // 读取并反序列化设置文件(先查大小上限,用受限的 JSON 读取器防深嵌套/超长字符串)。
private static AppSettings ReadFile(string path)
{
var info = new FileInfo(path);
@@ -151,6 +186,7 @@ namespace pacs_win_uia.Services
}
}
+ // 尽力写出文件:必要时先建目录;任何异常都只记警告并返回 false(不抛)。
private static bool TryWrite(string path, byte[] data)
{
try
@@ -171,6 +207,7 @@ namespace pacs_win_uia.Services
}
}
+ // 首选路径 = exe 同目录的 settings.json。
private static string GetExeDirectoryPath()
{
string directory = Path.GetDirectoryName(typeof(AppSettingsStore).Assembly.Location);
@@ -179,6 +216,7 @@ namespace pacs_win_uia.Services
FileName);
}
+ // 回退路径 = %LocalAppData%\pacs_win_uia\settings.json。
private static string GetUserDirectoryPath()
{
string directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
diff --git a/src/pacs_win_uia/Services/CommandRunner.cs b/src/pacs_win_uia/Services/CommandRunner.cs
index 2a4c368..601af27 100644
--- a/src/pacs_win_uia/Services/CommandRunner.cs
+++ b/src/pacs_win_uia/Services/CommandRunner.cs
@@ -1,3 +1,27 @@
+// =============================================================================
+// CommandRunner.cs —— 运行 settings.json 里配置的命令(本工具生命周期的钩子)
+//
+// 职责:
+// 按「执行时机」运行命令:启动(Start) / 退出(Exit) / 定时(Interval,可停) /
+// 单次(Once,只在启动时跑一次)。命令通过 cmd.exe /c 以当前用户身份运行。
+//
+// 被谁调用:
+// MainForm(启动时 RunStartCommands、退出时 RunExitCommands/Dispose);
+// 设置对话框的「立即执行」按钮调用 RunCommand。
+//
+// 关键语义 / 边界条件:
+// - 不注入目标进程、不提升权限;命令输出会原样记入日志,操作者不要把患者信息写进命令行。
+// - 命令进程加入 ProcessJob:退出时连同命令拉起的子进程一起结束(见 ProcessJob)。
+// - 单条命令有超时;超时会结束「整棵进程树」(taskkill /T),否则只杀 cmd.exe
+// 会把它拉起的应用留下。
+//
+// 输出事件:
+// Output 事件把每条命令的标准输出/标准错误实时抛给界面显示。
+//
+// 要改什么就改哪里:
+// 命令触发逻辑 -> RunByKind / StartContinuous。
+// 进程结束逻辑 -> Execute / KillProcessTree / KillRunningCommands。
+// =============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -10,8 +34,10 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // 命令实时输出事件的数据:命令名、一行输出、是否来自标准错误。
public sealed class CommandOutputEventArgs : EventArgs
{
+ // 构造输出事件参数。
public CommandOutputEventArgs(string name, string text, bool isError)
{
Name = name;
@@ -19,28 +45,39 @@ namespace pacs_win_uia.Services
IsError = isError;
}
+ // 命令名(用于界面区分是哪条命令的输出)。
public string Name { get; private set; }
+ // 输出的一行文本。
public string Text { get; private set; }
+ // true 表示来自标准错误(stderr)。
public bool IsError { get; private set; }
}
+ // 单条命令的执行结果汇总。
public sealed class CommandResult
{
+ // 命令名。
public string Name { get; set; }
+ // 进程是否成功启动。
public bool Started { get; set; }
+ // 是否因超时被结束。
public bool TimedOut { get; set; }
+ // 进程退出码(超时时无意义)。
public int ExitCode { get; set; }
+ // 标准输出全文。
public string Output { get; set; }
+ // 错误信息全文(启动失败、异常或标准错误)。
public string Error { get; set; }
}
+ // 命令执行器:按启动/退出/定时/单次时机执行配置的命令。
///
/// Runs the commands configured in settings.json as hooks of this tool's own lifetime:
/// 启动 / 退出 / on(按间隔持续执行,可停)/ once(只在启动时跑一次)。
@@ -51,17 +88,25 @@ namespace pacs_win_uia.Services
///
public sealed class CommandRunner : IDisposable
{
+ // 统一保护本类可变状态的锁。
private readonly object _sync = new object();
+ // 定时(on)命令的计时器集合;非空表示持续命令正在运行。
private readonly List _continuousTimers = new List();
+ // 正在执行的命令(按命令行去重),防止同一条慢命令自己叠加执行。
private readonly HashSet _inFlight = new HashSet(StringComparer.Ordinal);
+ // 仍在运行的进程表,退出时可据此结束它们,避免残留。
/// Processes still running, so exit can end them instead of leaving them behind.
private readonly Dictionary _running = new Dictionary();
+ // 作业对象:本工具退出(含崩溃)时连同命令拉起的整棵进程树一起结束。
/// Kills the whole command tree when this tool goes away, including a crash.
private readonly ProcessJob _job = new ProcessJob();
+ // 是否已释放。
private bool _disposed;
+ // 命令实时输出事件(每读到一行输出触发一次)。
public event EventHandler Output;
+ // 是否存在正在运行的定时(on)命令。
public bool IsContinuousRunning
{
get
@@ -73,6 +118,7 @@ namespace pacs_win_uia.Services
}
}
+ // 启动时机:先跑「启动(Start)」,再跑「单次(Once)」,最后启动「定时(Interval)」计时器。
public void RunStartCommands(AppSettings settings)
{
RunByKind(settings, CommandTriggerKind.Start);
@@ -80,12 +126,14 @@ namespace pacs_win_uia.Services
StartContinuous(settings);
}
+ // 退出时机:先停掉所有定时器,再跑「退出(Exit)」命令。
public void RunExitCommands(AppSettings settings)
{
StopContinuous();
RunByKind(settings, CommandTriggerKind.Exit);
}
+ // 运行所有启用且时机匹配的命令组(同一种时机可以有多个组)。
/// Runs every enabled command in the groups that use the given moment.
public void RunByKind(AppSettings settings, CommandTriggerKind kind)
{
@@ -106,6 +154,7 @@ namespace pacs_win_uia.Services
}
}
+ // 为每条「定时(Interval)」命令建一个 WinForms Timer,按间隔在后台线程执行(不阻塞 UI)。
public void StartContinuous(AppSettings settings)
{
StopContinuous();
@@ -138,6 +187,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全取命令组列表;配置缺失时返回空列表而不是 null。
private static IEnumerable Triggers(AppSettings settings)
{
if (settings == null || settings.Commands == null || settings.Commands.Triggers == null)
@@ -148,6 +198,7 @@ namespace pacs_win_uia.Services
return settings.Commands.Triggers;
}
+ // 停止并释放所有定时器(可重复调用;没有定时器时是空操作)。
public void StopContinuous()
{
List timers;
@@ -169,6 +220,8 @@ namespace pacs_win_uia.Services
}
}
+ // 执行一条命令并等待结束;设置对话框的「立即执行」也走这里。
+ // 用 _inFlight 去重:同一条命令上一次还没结束就跳过本次。
/// Runs one command and waits; used by the settings dialog's "立即执行" button.
public CommandResult RunCommand(CommandDefinition command, string trigger)
{
@@ -206,6 +259,7 @@ namespace pacs_win_uia.Services
}
}
+ // 真正启动进程:cmd.exe /c 执行命令,重定向输出、加入作业、按超时结束进程树。
private CommandResult Execute(CommandDefinition command, string trigger, CommandResult result)
{
var info = new ProcessStartInfo("cmd.exe", "/c " + command.CommandLine)
@@ -288,6 +342,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 记录一个正在运行的命令进程,供退出时结束。
private void TrackRunning(Process process)
{
lock (_sync)
@@ -296,6 +351,7 @@ namespace pacs_win_uia.Services
}
}
+ // 命令结束(或超时被结束)后从运行表移除。
private void UntrackRunning(Process process)
{
lock (_sync)
@@ -304,6 +360,8 @@ namespace pacs_win_uia.Services
}
}
+ // 结束一条命令进程「及其子进程」(命令可能拉起了应用)。
+ // 用 taskkill /T 遍历进程树;只 Kill 会留下应用在运行、且操作者看不到它从哪来。
///
/// Ends a command process *and its children* (a command may have launched an application).
/// taskkill /T walks the tree; a plain Kill would only take down cmd.exe and leave the
@@ -361,6 +419,7 @@ namespace pacs_win_uia.Services
}
}
+ // 结束所有仍在运行的命令;退出时调用,且在关闭作业之前。
/// Ends every command that is still running. Called on exit, before the job is closed.
public int KillRunningCommands()
{
@@ -385,6 +444,7 @@ namespace pacs_win_uia.Services
return killed;
}
+ // 解析命令的工作目录:配置且存在则用它,否则退回 exe 所在目录。
private static string ResolveWorkingDirectory(string configured)
{
if (!string.IsNullOrWhiteSpace(configured) && Directory.Exists(configured))
@@ -396,6 +456,7 @@ namespace pacs_win_uia.Services
return string.IsNullOrEmpty(exeDirectory) ? Directory.GetCurrentDirectory() : exeDirectory;
}
+ // 便捷执行:把一行命令包成默认超时 30 秒的 CommandDefinition 后同步执行。
private void RunSimple(string trigger, string commandLine)
{
if (string.IsNullOrWhiteSpace(commandLine))
@@ -408,12 +469,14 @@ namespace pacs_win_uia.Services
trigger);
}
+ // 把(定时)命令放到线程池后台执行,避免阻塞 UI 线程。
private void RunCommandInBackground(CommandDefinition command, string trigger)
{
// Continuous commands must not block the UI thread.
ThreadPool.QueueUserWorkItem(delegate { RunCommand(command, trigger); });
}
+ // 触发 Output 事件(先复制再调用,避免订阅者在回调里修改订阅列表)。
private void Raise(string name, string text, bool isError)
{
EventHandler handler = Output;
@@ -423,6 +486,7 @@ namespace pacs_win_uia.Services
}
}
+ // 释放:停定时器 -> 结束仍在运行的命令 -> 关闭作业(连带清掉命令拉起的进程)。
public void Dispose()
{
if (_disposed)
diff --git a/src/pacs_win_uia/Services/ControlLocatorBuilder.cs b/src/pacs_win_uia/Services/ControlLocatorBuilder.cs
index 4c461da..59453bd 100644
--- a/src/pacs_win_uia/Services/ControlLocatorBuilder.cs
+++ b/src/pacs_win_uia/Services/ControlLocatorBuilder.cs
@@ -5,40 +5,84 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // ============================================================================
+ // ControlLocatorBuilder —— 从一次控件快照里“生成”监控定义要保存的定位信息。
+ //
+ // 职责:
+ // - 把拾取到的控件转成一条可保存的监控定义:窗口定位字段(进程名/类名/标题关键词)、
+ // 绝对 XPath(DisplayPath)、取值键与当前值;
+ // - 用 ControlPath 生成路径后“立刻回读”校验(SelectUnique),只有能唯一走回同一个节点才算完整。
+ //
+ // 被谁调用:界面“拾取控件 / 添加当前控件”、点选取值、以及需要把节点导出成监控条目的地方。
+ //
+ // 为什么和 ControlLocatorService 放在一起:
+ // 生成路径与回读路径必须共用同一套匹配逻辑——生成时能走的路径,回读时才能走回来。
+ // 两边都只依赖 ControlPath(同一份映射 / 序号 / 转义规则),任何一侧单独改动都会让已存路径失效。
+ // 所以“生成”和“回读”刻意摆在相邻文件,方便对照维护。
+ //
+ // 要改什么就改哪里:
+ // - 窗口定位字段:ApplyWindowFields / ShortenTitle;
+ // - 页面特征文本:DescribePageFeatures / FormatPageFeatures;
+ // - 从 UIA 元素生成路径:BuildFromUia(按 RuntimeId 在 canonical RawView 树里找唯一目标);
+ // - 纯快照生成(无跨进程读取):BuildFromTree(根节点自身也可保存);
+ // - 完整性与稳定性提示:DescribeStability。
+ //
+ // 关键约定:
+ // - 旧的结构化路径字段(UiaPath / MsaaPathKey / Win32Path 等)已停用:新保存一律只写 DisplayPath,
+ // 旧字段留空,不再作为回退方案执行。
+ // - 窗口定位总是用“顶层窗口”,不会用子窗口类名,否则下次运行找不到窗口。
+ // - DisplayPath 是权威值;生成后立即 SelectUnique 回读,只有命中同一个节点 IsComplete 才为 true。
+ // ============================================================================
/// What a control snapshot contributes to a monitor definition.
public sealed class ControlLocatorBuildResult
{
+ // Source:这条定义要用哪个来源重新定位(Uia / Msaa / Win32 / Auto)。
public ControlSourcePreference Source { get; set; }
+ // ProcessName:顶层窗口所属进程名,用于无 HWND 时找回窗口。
public string ProcessName { get; set; }
+ // WindowClass:顶层窗口类名,与进程名/标题关键词一起定位窗口。
public string WindowClass { get; set; }
+ // WindowTitleKeyword:顶层窗口标题关键词(前缀截断后做包含匹配)。
public string WindowTitleKeyword { get; set; }
+ // UiaPath:旧 UIA 结构化路径(已停用,仅兼容保留,不执行、不再写入)。
public List UiaPath { get; set; }
+ // MsaaPathKey:旧 MSAA 合成键(已停用,仅兼容保留)。
public string MsaaPathKey { get; set; }
+ // Win32Path:旧 Win32 结构化路径(已停用,仅兼容保留)。
public List Win32Path { get; set; }
+ // DisplayPath:权威绝对 XPath(含真实窗口根),新保存只用它重新定位。
/// Authoritative absolute XPath for every source.
public string DisplayPath { get; set; }
+ // RuntimeId:拾取时元素的 UIA RuntimeId,仅作线索(目标程序重启后会变)。
public string RuntimeId { get; set; }
+ // ValueKey:要读取的属性名;为空表示只定位不取值。
public string ValueKey { get; set; }
+ // Value:本次生成的当前值(动态字段,不写入定义文件)。
public string Value { get; set; }
+ // IsComplete:路径是否已在当前快照里唯一命中同一个节点(才能真正用于定位)。
public bool IsComplete { get; set; }
+ // UiaPathFromInnerWindow:旧标志,仅为兼容反序列化保留;新路径始终包含实际窗口根。
/// Legacy compatibility flag; new paths always include the actual window root.
public bool UiaPathFromInnerWindow { get; set; }
+ // Note:生成结果的说明 / 告警(不完整原因或稳定性提示)。
public string Note { get; set; }
}
+ // ControlLocatorBuilder:生成监控定义的定位信息;与 ControlLocatorService 成对维护,
+ // 两侧共用 ControlPath 的映射/序号/转义规则,保证“生成得出、回读得到”的是同一节点。
///
/// Builds the re-resolution locator for a control. The builder and the resolver live next to each
/// other on purpose: a path that cannot be walked back is worthless, so both sides must agree on
@@ -48,16 +92,20 @@ namespace pacs_win_uia.Services
{
private readonly NativeWindowService _windowService;
+ // 无参构造:使用默认的 NativeWindowService。
public ControlLocatorBuilder()
: this(new NativeWindowService())
{
}
+ // 构造:注入 NativeWindowService(便于测试或替换实现)。
public ControlLocatorBuilder(NativeWindowService windowService)
{
_windowService = windowService ?? throw new ArgumentNullException("windowService");
}
+ // ApplyWindowFields:把“顶层窗口”的进程名/类名/标题关键词写进结果;传入子窗口时会用
+ // GetAncestor(GA_ROOT) 上溯到顶层——只有顶层窗口的字段下次运行才再匹配得上。
///
/// Window fields always describe the TOP-LEVEL window: matching by a renderer child class
/// would never find the window again on the next run.
@@ -85,6 +133,8 @@ namespace pacs_win_uia.Services
result.ProcessName = topLevel.ProcessName;
}
+ // DescribePageFeatures:把窗口描述成“进程=…;标题关键词=…;窗口类=…”文本,正好是监控条目
+ // 保存的页面特征,操作员可原样复制进悬浮条条件。
///
/// "进程=…;标题关键词=…;窗口类=…" for a window: exactly the values a monitor entry stores as
/// its page features, so the operator can copy them into a floating bar condition.
@@ -102,6 +152,7 @@ namespace pacs_win_uia.Services
return FormatPageFeatures(result);
}
+ // FormatPageFeatures:按“进程 / 标题关键词 / 窗口类”顺序拼装页面特征文本,空值跳过;全空返回 null。
public static string FormatPageFeatures(ControlLocatorBuildResult locator)
{
if (locator == null)
@@ -138,6 +189,8 @@ namespace pacs_win_uia.Services
return text.Length == 0 ? null : text.ToString();
}
+ // BuildFromUia:读取与解析时相同的 canonical RawView 窗口树,按 RuntimeId(或元素引用相等)找唯一节点,
+ // 再交给 BuildFromTree 生成路径;出现多个相同身份或目标不在树中都判失败,不虚构层级。
/// Captures the same canonical RawView window tree used by resolution.
public ControlLocatorBuildResult BuildFromUia(UiaElementInfo element, NativeWindowInfo window)
{
@@ -189,6 +242,8 @@ namespace pacs_win_uia.Services
}
}
+ // BuildFromTree:纯快照生成(不做 UIA/HWND/RuntimeId 等任何跨进程读取),window 应是已捕获的顶层窗口,
+ // 根节点自身也可保存;生成 DisplayPath 后立即 SelectUnique 回读确认,并写入 IsComplete 与稳定性提示。
///
/// Pure snapshot builder: no UIA, HWND, runtime-id or other cross-process reads.
/// window should be the already-captured top-level window. The root itself is saveable.
@@ -240,6 +295,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // Preference:控件来源 → 保存的来源偏好映射(默认 Uia)。
private static ControlSourcePreference Preference(ControlTreeSource source)
{
switch (source)
@@ -250,6 +306,8 @@ namespace pacs_win_uia.Services
}
}
+ // DescribeStability:统计路径里有多少段缺少稳定 AutomationId、用了类名、依赖序号,
+ // 生成“仅保证当前快照唯一、跨版本不保证稳定”的提示文本。
private static string DescribeStability(IList chain)
{
int withoutId = 0;
@@ -277,6 +335,7 @@ namespace pacs_win_uia.Services
return note;
}
+ // BuildFromMsaa:读取 MSAA 树并按 PathKey 唯一定位目标后生成路径。
public ControlLocatorBuildResult BuildFromMsaa(MsaaNodeInfo node, NativeWindowInfo window)
{
return CaptureAndBuild(ControlTreeSource.Msaa, window, delegate(ControlTreeNode candidate)
@@ -286,6 +345,7 @@ namespace pacs_win_uia.Services
});
}
+ // BuildFromWin32:读取 Win32 树并按窗口句柄唯一定位目标后生成路径。
public ControlLocatorBuildResult BuildFromWin32(NativeWindowInfo target, NativeWindowInfo window)
{
return CaptureAndBuild(ControlTreeSource.Win32, window ?? target, delegate(ControlTreeNode candidate)
@@ -294,6 +354,8 @@ namespace pacs_win_uia.Services
});
}
+ // CaptureAndBuild:UIA/MSAA/Win32 共用的“读树 → 用谓词找唯一目标 → BuildFromTree”流程;
+ // 匹配到多个或一个都找不到都失败,不生成替代路径。
private ControlLocatorBuildResult CaptureAndBuild(ControlTreeSource source, NativeWindowInfo window, Predicate matches)
{
var failure = new ControlLocatorBuildResult { Source = Preference(source) };
@@ -326,12 +388,14 @@ namespace pacs_win_uia.Services
catch (Exception ex) { failure.Note = "读取 " + source + " 窗口树失败:" + ex.Message; return failure; }
}
+ // DescribePathFromTree:直接用内存快照生成绝对 XPath(含窗口根),与保存使用的规则一致。
/// Shared in-memory absolute XPath, including the window root.
public static string DescribePathFromTree(ControlTreeNode root, ControlTreeNode node)
{
return ControlPath.Build(root, node);
}
+ // BuildNodeChain:在树里自顶向下找 target,把 root→target 的路径填入 chain;找到返回 true,否则回退栈并返回 false。
private static bool BuildNodeChain(ControlTreeNode root, ControlTreeNode target, IList chain)
{
chain.Add(root);
@@ -352,6 +416,7 @@ namespace pacs_win_uia.Services
return false;
}
+ // ShortenTitle:把标题截成前 24 个字符当关键词(标题会随文件名/数据变化,前缀更稳)。
/// Titles change (file names, patient counts); a prefix is a stabler keyword.
private static string ShortenTitle(string title)
{
diff --git a/src/pacs_win_uia/Services/ControlLocatorService.cs b/src/pacs_win_uia/Services/ControlLocatorService.cs
index b2ea425..26c62a3 100644
--- a/src/pacs_win_uia/Services/ControlLocatorService.cs
+++ b/src/pacs_win_uia/Services/ControlLocatorService.cs
@@ -5,42 +5,82 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // ============================================================================
+ // ControlLocatorService —— 无界面地“回读”一条已保存的监控定义:先找窗口,再做控件定位。
+ //
+ // 职责:
+ // 1) FindTargetWindow:按 进程名 + 窗口类名 + 标题关键词 找到目标“顶层窗口”;
+ // 2) Resolve / ResolveFromTree:在指定来源的快照上执行 ControlPath 的 XPath,返回同一个控件节点。
+ //
+ // 被谁调用:悬浮条 / 无界面监控(--head-only)、以及需要重新定位控件的界面动作。
+ //
+ // 与 ControlLocatorBuilder 的关系(为什么相邻):
+ // 生成路径与回读路径必须共用同一套匹配逻辑(都走 ControlPath)。任何一侧单独改动
+ // 映射 / 序号 / 转义规则,都会让已保存的路径读不回来,所以两者刻意摆在一起对照维护。
+ //
+ // 关键约定:
+ // - XPath 是权威:ControlPath 缺失、旧 path 文本或旧结构化字段都一律不执行、不回退。
+ // - 显式来源(Uia/Msaa/Win32)绝不跨来源回退;只有 Auto 会在求值前选一个可用来源。
+ // - ResolveFromTree 返回 canonical 树中的“同一个”节点,值读取直接用该节点携带的 payload,避免二次查找。
+ // - 窗口定位分级(4→1,从精确到宽松依次尝试),并要求“唯一匹配”;多个候选直接失败,让人补充条件。
+ // - 窗口类名可能随程序升级变化、标题可能随数据变化,所以允许降级匹配,但会标记为需要人工核对。
+ //
+ // 要改什么就改哪里:
+ // - 窗口匹配逻辑:MatchesWindow / FindTargetWindow;
+ // - 控件定位:Resolve / ResolveFromTree;
+ // - 元素同一性判定:SameElement(RuntimeId 优先,不同即不等)。
+ // ============================================================================
+ // ControlResolution:一次“回读”的结果——是否找到、命中的来源与节点、窗口句柄、是否用了宽松匹配、错误信息。
/// Result of resolving one saved control.
public sealed class ControlResolution
{
+ // Found:是否唯一命中并成功定位。
public bool Found { get; set; }
+ // ResolvedSource:实际命中的控件来源(Auto 时由快照决定;显式来源时等于定义来源)。
public ControlTreeSource ResolvedSource { get; set; }
+ // Node:命中的控件节点;值读取直接使用它携带的 per-source payload(UIA/MSAA/Win32),无需再查一次。
/// The resolved node; carries the per-source payload the value reader needs.
public ControlTreeNode Node { get; set; }
+ // WindowHandle:目标顶层窗口句柄,定位与取值都在它对应的快照上进行。
public IntPtr WindowHandle { get; set; }
+ // UsedFallback:窗口是用较宽规则(级别 ≤2)匹配到的,路径段绝不跳过,但结果需人工核对。
///
/// True when the window was found through a wide match. Path segments are never skipped.
///
public bool UsedFallback { get; set; }
+ // Error:失败原因;成功时为 null。
public string Error { get; set; }
}
+ // ControlLocatorService:无界面回读服务。定位完全依赖 进程名+窗口类名+标题关键词 找窗口,
+ // 再用 XPath 在快照上选控件,不依赖“窗口此刻已存在”这一前提。
///
/// Re-resolves a saved control without any UI. Nothing here depends on a window existing: a saved
/// control is located through 进程名 + 窗口类名 + 标题关键词, then selected with XPath over a snapshot of the requested source.
///
public sealed class ControlLocatorService
{
+ // 窗口枚举 / 捕获服务(找顶层窗口、取窗口信息)。
private readonly NativeWindowService _windowService;
+ // UIA 读取服务(Auto 或显式 UIA 来源时读控件树)。
private readonly UiAutomationService _uiAutomationService;
+ // MSAA 读取服务。
private readonly MsaaService _msaaService;
+ // Win32 树读取器。
private readonly Win32TreeReader _win32TreeReader;
+ // 无参构造:使用各默认服务。
public ControlLocatorService()
: this(new NativeWindowService(), new UiAutomationService(), new MsaaService(), new Win32TreeReader())
{
}
+ // 构造:注入全部服务(便于测试或替换实现)。
public ControlLocatorService(
NativeWindowService windowService,
UiAutomationService uiAutomationService,
@@ -55,6 +95,8 @@ namespace pacs_win_uia.Services
// ------------------------------------------------------------------ top-level window
+ // FindTargetWindow:按进程名 / 窗口类名 / 标题关键词找保存控件的顶层窗口;三者可选,填得越多越精确。
+ // 匹配要求唯一,多个候选直接报错让人补充条件;找不到时返回 Zero。
///
/// Finds the saved control's top-level window by process name, class name and title keyword.
/// All three are optional but the more that are filled the more precise the match.
@@ -140,11 +182,15 @@ namespace pacs_win_uia.Services
return best;
}
+ // 窗口匹配级别上限:4 = 进程+类+标题,3 = 进程+类,2 = 进程+标题,1 = 仅进程。
private const int MatchingLevels = 4;
+ // 记录上次 FindTargetWindow 的匹配级别,用于标记“弱匹配、需人工核对”。
/// Match level of the last FindTargetWindow call; used to flag weak matches.
private int _lastWindowMatchLevel;
+ // MatchesWindow:按级别判断窗口是否匹配;级别越高条件越多。
+ // 仅进程名一级,若没填类名/标题则拒绝(否则会命中所有窗口);类名比标题更具区分度,故只有一个能保留时留类名。
///
/// 4 = process+class+title, 3 = process+class, 2 = process+title, 1 = process only.
/// Class comes before title when only one can be kept: class names are far more distinctive
@@ -188,6 +234,7 @@ namespace pacs_win_uia.Services
}
}
+ // DescribeMatchLevel:把匹配级别转成中文说明(用于日志与弱匹配提示)。
private static string DescribeMatchLevel(int level)
{
switch (level)
@@ -205,6 +252,8 @@ namespace pacs_win_uia.Services
// ------------------------------------------------------------------ control resolution
+ // Resolve:读取目标窗口的控件快照并定位控件;XPath 权威,显式来源绝不回退到别的树,
+ // Auto 会在求值前先选一个可用来源,求值失败也不换来源重试。
/// XPath is authoritative. Explicit sources never fall back to a different tree.
public ControlResolution Resolve(ControlMonitorDefinition definition, IntPtr windowHandle, IList steps)
{
@@ -243,6 +292,8 @@ namespace pacs_win_uia.Services
}
}
+ // ResolveFromTree:纯快照解析(所有来源共用)。返回 canonical 树里被选中的“那个”节点及其 payload;
+ // 旧 path 文本 / 结构化字段一律不执行,即使 ControlPath 缺失;要求唯一命中,且快照来源与定义来源一致。
///
/// Pure snapshot resolver for ALL sources. Returns the exact selected node with its payload.
/// Old path text/structured fields are never executed, even if ControlPath is missing.
@@ -278,6 +329,8 @@ namespace pacs_win_uia.Services
return result;
}
+ // SameElement:判定两个 AutomationElement 是否同一元素;RuntimeId 优先——两侧都有 id 时长度或任一值不同即不等,
+ // 绝不用相同的名字/类名/句柄来“救回”不同 id;两侧都无 id 时才退化为引用相等与属性比较(后者是更粗的近似)。
///
/// RuntimeId is authoritative. Different ids (including lengths) are NEVER rescued by
/// equal names/classes/handles. Without ids only reference identity proves equality.
diff --git a/src/pacs_win_uia/Services/ControlMonitorStore.cs b/src/pacs_win_uia/Services/ControlMonitorStore.cs
index c8d8be6..f172ea5 100644
--- a/src/pacs_win_uia/Services/ControlMonitorStore.cs
+++ b/src/pacs_win_uia/Services/ControlMonitorStore.cs
@@ -9,21 +9,50 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // ============================================================================
+ // ControlMonitorStore —— 监控定义的持久化(control-monitors.json)。
+ //
+ // 职责:把 ControlMonitorDefinition 列表读进 / 写出 JSON 文件;保存是显式的调用方动作。
+ //
+ // 被谁调用:监控列表界面、无界面监控、杂项工具(载入 / 保存定义)。
+ //
+ // 读取宽松、保存严格(核心约定):
+ // - Load:只做结构与大小校验,且保留旧记录供人工编辑——不自动迁移、不执行、不丢弃路径文本,
+ // 也不会替调用方改写或保存原文件;旧格式路径在校验时被豁免,好让文件还能打开去修。
+ // - Save:严格校验,拒绝包含旧格式 / 无效 path 的条目;用“临时文件 + 原子替换”写盘,
+ // 避免半截文件;空列表也绝不能悄悄清掉原文件里尚未修正的旧路径。
+ //
+ // 动态字段为什么“不持久化”:
+ // RuntimeId 重启后会变、生成出来的 PageFeatures 与窗口定位字段重复、Value 只是读取到的瞬时值——
+ // 它们都不是定义的一部分,所以 CopyDefinition 在保存前把它们清空 / 置空,只留下真正稳定的定位信息。
+ //
+ // 要改什么就改哪里:
+ // - 文件格式 / 版本:StoreDocument / CurrentVersion / CreateSerializer;
+ // - 读取规则:Load;写入与原子替换:Save;保存前字段裁剪:CopyDefinition;
+ // - 默认路径:GetDefaultFilePath。
+ // ============================================================================
+ // ControlMonitorStore:只负责持久化监控定义;保存是调用方的显式动作。
///
/// Persists monitor definitions only. Saving is an explicit caller action.
///
public sealed class ControlMonitorStore
{
+ // CurrentVersion:当前文件格式版本,Load 只接受该版本。
private const int CurrentVersion = 1;
+ // MaxDefinitions:定义条数上限(复用规则类的常量)。
private const int MaxDefinitions = ControlMonitorRules.MaxDefinitions;
+ // MaxFileBytes:文件大小上限(复用规则类的常量)。
private const int MaxFileBytes = ControlMonitorRules.MaxDocumentBytes;
+ // _filePath:已规范化(GetFullPath)的目标 JSON 文件绝对路径。
private readonly string _filePath;
+ // 无参构造:使用默认路径(LocalApplicationData\pacs_win_uia\control-monitors.json)。
public ControlMonitorStore()
: this(GetDefaultFilePath())
{
}
+ // 构造:指定文件路径;空路径直接抛异常。
public ControlMonitorStore(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
@@ -34,11 +63,14 @@ namespace pacs_win_uia.Services
_filePath = Path.GetFullPath(filePath);
}
+ // FilePath:当前使用的文件绝对路径。
public string FilePath
{
get { return _filePath; }
}
+ // Load:打开并反序列化文件;文件不存在返回空列表。做了大小限制、JSON 读取配额与版本 / 结构校验,
+ // 但路径语法只做“宽松”校验——旧格式路径被保留下来供人工修复,不迁移、不改写原文件。
public IList Load()
{
FileStream stream;
@@ -112,6 +144,8 @@ namespace pacs_win_uia.Services
}
}
+ // Save:保存定义列表。先复制并严格校验(拒绝旧格式 / 无效 path),再序列化到临时文件并原子替换目标文件;
+ // 绝不能覆盖不可读的已有文件,空列表也不允许悄悄清掉原文件里的旧路径(要么先修正,要么自行备份)。
public void Save(IEnumerable definitions)
{
if (definitions == null)
@@ -206,6 +240,7 @@ namespace pacs_win_uia.Services
}
}
+ // GetDefaultFilePath:返回默认文件路径(LocalApplicationData\pacs_win_uia\control-monitors.json)。
private static string GetDefaultFilePath()
{
string directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
@@ -216,11 +251,14 @@ namespace pacs_win_uia.Services
return Path.Combine(directory, "pacs_win_uia", "control-monitors.json");
}
+ // CreateSerializer:创建 StoreDocument 的 DataContract JSON 序列化器。
private static DataContractJsonSerializer CreateSerializer()
{
return new DataContractJsonSerializer(typeof(StoreDocument));
}
+ // CopyDefinition:逐字段显式复制,并清空“不持久化”的动态字段(RuntimeId、生成型 PageFeatures、
+ // UiaPath/MsaaPathKey/Win32Path 等);漏抄一个字段会静默存成 null,是编辑器最坏的失败模式。
///
/// Copies every field explicitly. A field that is forgotten here saves as null with no error
/// at all, which is the worst failure mode for an editor — the locator fields especially.
@@ -258,6 +296,7 @@ namespace pacs_win_uia.Services
return copy;
}
+ // TryValidate:暴露 store 用的同一套校验规则,供编辑器一次性列出所有问题,而不是靠抛异常。
///
/// Exposes the same rules the store enforces so the editor can show every problem at once
/// instead of relying on a thrown exception.
@@ -267,6 +306,7 @@ namespace pacs_win_uia.Services
return ControlMonitorRules.ValidateList(definitions);
}
+ // DescribeErrors:把校验错误拼成一句可读文本,最多列 5 条后汇总总数。
private static string DescribeErrors(IList errors)
{
const int MaxReported = 5;
@@ -290,12 +330,15 @@ namespace pacs_win_uia.Services
return builder.ToString();
}
+ // StoreDocument:文件根对象(版本 + 条目列表)。
[DataContract]
private sealed class StoreDocument
{
+ // Version:文件格式版本号。
[DataMember(Order = 1, IsRequired = true)]
public int Version { get; set; }
+ // Items:定义条目列表。
[DataMember(Order = 2, IsRequired = true)]
public List Items { get; set; }
}
diff --git a/src/pacs_win_uia/Services/ControlPath.cs b/src/pacs_win_uia/Services/ControlPath.cs
index 5ecb293..e32eaf1 100644
--- a/src/pacs_win_uia/Services/ControlPath.cs
+++ b/src/pacs_win_uia/Services/ControlPath.cs
@@ -7,12 +7,60 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // ============================================================================
+ // ControlPath —— 本项目“控件定位”的核心:把控件树快照当成一份 XML,用 XPath 1.0 选择控件节点。
+ //
+ // 职责:
+ // 1) 为每个控件节点生成稳定的绝对 XPath(PreparePaths / Build);
+ // 2) 校验用户填写的 XPath 语法(IsXPath / ValidateSyntax);
+ // 3) 在快照上执行 XPath 并映射回原始控件节点(Select / SelectUnique);
+ // 4) 判断快照是否完整、是否唯一可信(SnapshotError)。
+ //
+ // 被谁调用:
+ // - ControlLocatorBuilder:拾取控件时生成 DisplayPath,并立即回读校验(BuildFromTree);
+ // - ControlLocatorService:Resolve / ResolveFromTree 用 SelectUnique 重新定位已保存的控件;
+ // - ControlMonitorRules.ValidateControlPath、监控列表 / 杂项工具:校验与显示路径。
+ // 生成路径与回读路径共用这里的同一套规则,所以改匹配逻辑只改本文件即可,避免两边跑偏。
+ //
+ // 要改什么就改哪里:
+ // - XML 与控件节点的映射:AppendXml / TypeName / Name / AutomationId / ClassName;
+ // - 路径生成策略(选哪一段做主语):PreferredStep / IdentityKeys / HasIdentity;
+ // - 序号与预计算:PreparePaths;
+ // - 匹配语义(多结果 / 唯一):Select / SelectUnique;
+ // - 语法校验规则:IsXPath / ValidateSyntax。
+ //
+ // XPath 1.0 映射规则(XML 节点 ↔ 控件节点):
+ // - 一个 ControlTreeNode 对应一个 XML 元素:根元素固定为 Window;其余元素名 = TypeName(node)
+ // (UIA 取 ControlType 去 "ControlType." 前缀,MSAA=Accessible,Win32=Window),
+ // 再经 XmlConvert.EncodeLocalName 转义后作为元素名。
+ // - 根固定为 /Window[1]:无论选中哪个窗口,绝对路径都以 /Window[1] 开头;窗口身份
+ // (进程名 / 类名 / 标题关键词)由 ControlMonitorDefinition 另行提供,不写进路径。
+ // - 属性:每个元素都写 @Name / @AutomationId / @ClassName / @ControlType / @Source;
+ // MSAA 节点额外写 @Role / @Value。属性为空时写成空字符串。
+ // - 序号是 XPath 1.0 的位置谓词,从 1 开始(1-based);计数口径见 IdentityKeys:
+ // 类型序号统计“所有同类型兄弟”,ClassName 谓词也统计“会优先用 AutomationId 的同类型兄弟”。
+ // - contains/and:谓词里可使用 XPath 1.0 标准函数与运算符(contains()、and、or、@ 属性等),
+ // 由 .NET 标准 XPath 求值器解析,本类不自己实现表达式语法。
+ // - 引号与特殊字符转义:属性值用 Quote()(单引号串 / 双引号串 / 同时含单双引号时用 concat());
+ // 元素名用 XmlConvert.EncodeLocalName 转义。
+ // - 生成路径的稳定策略:AutomationId → 类型[ClassName] → 类型+序号;绝不自动使用会变的 Name,
+ // 因为 Name 常随数据/状态变化(按钮文字、列表行文本)。
+ //
+ // 重要语义:
+ // - PreparePaths 是线性预计算:一次自顶向下遍历就地算出每个节点的 CanonicalPath 与 CanonicalPathRoot,
+ // 之后 Build 直接取用;改动了快照要重新调用。
+ // - Select 返回“全部”匹配(文档顺序),0 个或出错时通过 error 返回诊断;SelectUnique 要求恰好 1 个,
+ // 多于 1 个视为定位不唯一而失败。
+ // - ValidateSyntax 只校验“语法 / 结果类型”,不读提供者、不检查匹配数量;并显式拒绝旧路径格式、
+ // 选择属性(@)与标量结果(字符串/数字/布尔),因为定位必须落到控件元素节点集。
+ // ============================================================================
///
/// XPath 1.0 over a snapshot. XML elements map to the ORIGINAL nodes, including source payloads.
/// The selected window is always /Window[1]; window identity is supplied separately.
///
public static class ControlPath
{
+ // IsXPath:只判断是不是“受支持的前缀”(/、//、./ 或括号开头),不做语法或唯一性校验。
/// Checks the supported expression prefix, not syntax or uniqueness.
public static bool IsXPath(string text)
{
@@ -22,6 +70,8 @@ namespace pacs_win_uia.Services
text.StartsWith("(", StringComparison.Ordinal);
}
+ // ValidateSyntax:只校验语法与结果类型(必须是节点集);合法返回 null,否则返回中文诊断。
+ // 不读提供者、不查匹配数量,并显式拒绝旧路径格式、选择属性(@)与标量结果。
///
/// Returns null for supported node-set XPath syntax, otherwise a Chinese diagnostic.
/// Does not read providers or check matches. Select additionally checks actual node kinds.
@@ -66,6 +116,7 @@ namespace pacs_win_uia.Services
catch (ArgumentException ex) { return "XPath 无效:" + ex.Message; }
}
+ // Quote:把字符串安全地写成 XPath 1.0 字符串字面量;同时含单双引号时用 concat() 拼接。
/// Quotes an XPath 1.0 string, including values containing both kinds of quote.
public static string Quote(string value)
{
@@ -75,6 +126,8 @@ namespace pacs_win_uia.Services
return "concat('" + value.Replace("'", "',\"'\",'") + "')";
}
+ // PreparePaths:线性预计算——一次自顶向下遍历,为每个节点就地算出 CanonicalPath(根固定 /Window[1])
+ // 与 CanonicalPathRoot;改动快照后需重跑,Build 依赖这份缓存。
/// Linear sibling work plus output size. Re-run after modifying the snapshot.
public static void PreparePaths(ControlTreeNode root)
{
@@ -103,6 +156,7 @@ namespace pacs_win_uia.Services
}
}
+ // Build:取节点在 root 快照下的绝对路径;若节点未针对该 root 预计算过则先 PreparePaths,仍不匹配则返回 null。
public static string Build(ControlTreeNode root, ControlTreeNode node)
{
if (root == null || node == null) return null;
@@ -110,6 +164,7 @@ namespace pacs_win_uia.Services
return ReferenceEquals(node.CanonicalPathRoot, root) ? node.CanonicalPath : null;
}
+ // Select:在快照上执行 XPath,按文档顺序返回“全部”匹配的控件节点;语法错、树为空、选中属性/文本、0 匹配都写入 error。
/// All element matches in document order; errors and zero matches set error.
public static IList Select(ControlTreeNode root, string text, out string error)
{
@@ -140,6 +195,7 @@ namespace pacs_win_uia.Services
return found;
}
+ // SelectUnique:要求恰好匹配 1 个控件;0 个或多个都视为“定位不唯一”而失败,供定位场景使用。
public static ControlTreeNode SelectUnique(ControlTreeNode root, string text, out string error)
{
IList nodes = Select(root, text, out error);
@@ -149,6 +205,7 @@ namespace pacs_win_uia.Services
return null;
}
+ // SnapshotError:检查整棵树是否来源一致且子节点完整(有些读取器不会把下层的不完整冒泡到根);不满足则返回中文诊断。
/// Readers do not all propagate incomplete descendants to the root.
internal static string SnapshotError(ControlTreeNode root)
{
@@ -165,6 +222,7 @@ namespace pacs_win_uia.Services
return null;
}
+ // TypeName:决定 XML 元素名——Win32→"Window"、MSAA→"Accessible"、UIA→去掉 "ControlType." 前缀的控件类型(空则 "Control")。
private static string TypeName(ControlTreeNode node)
{
if (node.Source == ControlTreeSource.Win32) return "Window";
@@ -174,6 +232,7 @@ namespace pacs_win_uia.Services
type.StartsWith("ControlType.", StringComparison.Ordinal) ? type.Substring(12) : type;
}
+ // Name:按来源取显示名(UIA=Name、MSAA=accName、Win32=窗口标题);只作 XML 的 @Name 属性,不参与生成路径。
private static string Name(ControlTreeNode node)
{
switch (node.Source)
@@ -184,22 +243,26 @@ namespace pacs_win_uia.Services
}
}
+ // AutomationId:仅 UIA 有 AutomationId;这是生成路径的首选稳定标识。
private static string AutomationId(ControlTreeNode node)
{
return node.Source == ControlTreeSource.Uia && node.Uia != null ? node.Uia.AutomationId : null;
}
+ // ClassName:UIA 取 Uia.ClassName,Win32 取窗口类名;MSAA 无类名。
private static string ClassName(ControlTreeNode node)
{
if (node.Source == ControlTreeSource.Uia) return node.Uia == null ? null : node.Uia.ClassName;
return node.Source == ControlTreeSource.Win32 && node.Window != null ? node.Window.ClassName : null;
}
+ // HasIdentity:有 AutomationId 或 ClassName 之一即算“有身份”,可作路径主语;否则只能退化为类型+序号。
private static bool HasIdentity(ControlTreeNode node)
{
return !string.IsNullOrEmpty(AutomationId(node)) || !string.IsNullOrEmpty(ClassName(node));
}
+ // Increment:字典计数自增(统计同类型/同类谓词的兄弟数量,决定是否需要序号)。
private static void Increment(IDictionary counts, string key)
{
int count;
@@ -207,6 +270,8 @@ namespace pacs_win_uia.Services
counts[key] = count + 1;
}
+ // IdentityKeys:列出该节点参与计数的“身份键”——纯类型、类型[@ClassName=…]、类型[@AutomationId=…];
+ // 用于算序号,故类型序号统计所有同类型兄弟,ClassName 谓词也统计会优先用 AutomationId 的同类型兄弟。
// A class predicate must also count siblings which prefer an AutomationId. Bare type
// indices likewise count ALL same-type siblings, including siblings with identities.
private static IEnumerable IdentityKeys(ControlTreeNode node)
@@ -217,6 +282,7 @@ namespace pacs_win_uia.Services
if (!string.IsNullOrEmpty(AutomationId(node))) yield return type + "[@AutomationId=" + Quote(AutomationId(node)) + "]";
}
+ // PreferredStep:生成单步主语的稳定策略——优先 [@AutomationId=…],其次 [@ClassName=…],最后退回纯类型;不自动用 Name。
private static string PreferredStep(ControlTreeNode node)
{
string step = XmlConvert.EncodeLocalName(TypeName(node));
@@ -224,6 +290,8 @@ namespace pacs_win_uia.Services
return string.IsNullOrEmpty(ClassName(node)) ? step : step + "[@ClassName=" + Quote(ClassName(node)) + "]";
}
+ // AppendXml:把控件树递归写成 XML 快照,并建立 XML 节点→控件节点的映射供 Select 反查。
+ // 根元素固定 Window,属性见 @Name/@AutomationId/@ClassName/@ControlType/@Source(MSAA 另加 @Role/@Value)。
private static void AppendXml(XmlNode parent, ControlTreeNode node, IDictionary mapping)
{
XmlDocument document = parent as XmlDocument ?? parent.OwnerDocument;
diff --git a/src/pacs_win_uia/Services/ControlTreeExporter.cs b/src/pacs_win_uia/Services/ControlTreeExporter.cs
index 652ab99..f1a966a 100644
--- a/src/pacs_win_uia/Services/ControlTreeExporter.cs
+++ b/src/pacs_win_uia/Services/ControlTreeExporter.cs
@@ -1,3 +1,16 @@
+// =============================================================================
+// ControlTreeExporter —— 控件树快照的 JSON 导出(DataContractJsonSerializer)。
+// 职责:把 ControlTreeNode 快照写成文件或内存字符串。只序列化快照 DTO,绝不序列化活动对象
+// (HWND、AutomationElement、IAccessible 一律不落盘,否则反序列化会失败或间接拖住目标进程)。
+// ControlTreeDocument 额外记录每个来源是否出现,方便阅读方区分“真正读到的控件”与“仅 Win32 兜底的节点”。
+// 被谁调用:UI/MainForm.cs 的导出按钮(_treeExporter.Export / Serialize)。
+// 线程模型:纯 CPU/IO,不跨进程、不阻塞在 COM 上;调用点在 UI 线程(保存对话框回调),但它导出的
+// 是早就读好的快照,因此无需独立线程。若将来要导出超大文档,应移到后台线程。
+// 要改什么就改哪里:
+// - 改导出字段/顺序 → 本文件的 [DataMember(Order=...)]。
+// - 改序列化器 → WriteObject / Serialize。
+// =============================================================================
+
using System;
using System.IO;
using System.Runtime.Serialization;
@@ -6,6 +19,7 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // 导出文档根对象:时间戳、请求来源、三来源可用标志、树根。
///
/// The exported control-tree document. Every node carries its source, so a Win32-only node can
/// never be mistaken for a control that was actually read.
@@ -13,32 +27,40 @@ namespace pacs_win_uia.Services
[DataContract]
public sealed class ControlTreeDocument
{
+ // 导出时刻(UTC)。
[DataMember(Order = 1)]
public DateTime ExportedAtUtc { get; set; }
+ // 请求的来源(可空);自动模式为 null,不序列化(EmitDefaultValue=false)。
/// Null when auto mode was used.
[DataMember(Order = 2, EmitDefaultValue = false)]
public ControlTreeSource? RequestedSource { get; set; }
+ // 树中是否出现过 UIA 节点。
[DataMember(Order = 3)]
public bool UiaAvailable { get; set; }
+ // 树中是否出现过 MSAA 节点。
[DataMember(Order = 4)]
public bool MsaaAvailable { get; set; }
+ // 树中是否出现过 Win32 节点。
[DataMember(Order = 5)]
public bool Win32Available { get; set; }
+ // 控件树根节点快照。
[DataMember(Order = 6)]
public ControlTreeNode Root { get; set; }
}
+ // 只把快照 DTO 序列化,不持有任何活动对象。
///
/// Exports only snapshot DTOs. Live HWND, AutomationElement and IAccessible instances are never
/// serialized.
///
public sealed class ControlTreeExporter
{
+ // 把整棵树连同来源标志写成 JSON 文件。
public void Export(ControlTreeNode tree, ControlTreeSource? source, string filePath)
{
if (tree == null)
@@ -57,6 +79,7 @@ namespace pacs_win_uia.Services
}, filePath);
}
+ // 把整棵树序列化成 UTF-8 JSON 字符串(不落盘)。
public string Serialize(ControlTreeNode tree, ControlTreeSource? source)
{
if (tree == null)
@@ -77,6 +100,7 @@ namespace pacs_win_uia.Services
return Serialize(document);
}
+ // 递归判断树中是否存在某来源的节点,用于填充 *Available 标志。
private static bool ContainsSource(ControlTreeNode node, ControlTreeSource source)
{
if (node == null)
@@ -100,6 +124,7 @@ namespace pacs_win_uia.Services
return false;
}
+ // 确保目录存在后用 FileStream 覆盖写出完整 JSON。
private static void WriteObject(object value, string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
@@ -121,6 +146,7 @@ namespace pacs_win_uia.Services
}
}
+ // 用内存流序列化并转 UTF-8 字符串。
private static string Serialize(object value)
{
var serializer = new DataContractJsonSerializer(value.GetType());
diff --git a/src/pacs_win_uia/Services/ControlTreeService.cs b/src/pacs_win_uia/Services/ControlTreeService.cs
index 8c3c9d4..8a8b242 100644
--- a/src/pacs_win_uia/Services/ControlTreeService.cs
+++ b/src/pacs_win_uia/Services/ControlTreeService.cs
@@ -1,3 +1,21 @@
+// =============================================================================
+// ControlTreeService —— 三种控件树来源的统一入口。
+// 职责:把 UIA / MSAA / Win32 三个独立视图收敛成一个 ControlTreeResult。“自动”模式按
+// UIA→MSAA→Win32 顺序尝试,取第一个“不只根节点”的来源;Win32 是地板(本地枚举,不会挂)。
+// 只有根节点(nodeCount<=1)才视为“没内容”,因此只暴露根节点的来源会被跳过。
+// 被谁调用:UI/MainForm.cs 的 BeginTreeRead / LiveTreeTimerOnTick(都跑在 LongRunning 专用线程)。
+// 线程模型:Read 内部会发起跨进程调用,必须运行在独立线程(MainForm 用 TaskCreationOptions.LongRunning)。
+// 取消是协作式的:Auto 循环在每次尝试前检查 CancellationToken,单个读取器内部用 ReadBudget 在
+// 调用间隙检查——在途的跨进程调用无法中断,所以取消只能“尽快停止发起新工作”,不能抢占。
+// ReadUia 里 ChromeContentRetryDelayMs 的 Thread.Sleep 发生在这个后台线程上做有界等待,
+// 绝不能挪到 UI 线程。
+// 要改什么就改哪里:
+// - 改来源顺序 → AutoOrder。
+// - 改“算不算读到内容” → ReadOne 里的 hasContent。
+// - 改 UWP/浏览器边框重读 → ReadUia / LooksLikeChromeOnly。
+// - 注意:读完后统一 ControlPath.PreparePaths;绝不自动用内层窗口替换根(会伪造出另一套绝对层级)。
+// =============================================================================
+
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -8,20 +26,27 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // 一次读取的汇总结果:根、实际来源、是否成功、说明、节点数。
public sealed class ControlTreeResult
{
+ // 读到的树根;失败时可为 null。
public ControlTreeNode Root { get; set; }
+ // 实际使用的来源。
public ControlTreeSource UsedSource { get; set; }
+ // 是否读到了“超出根”的内容。
public bool Succeeded { get; set; }
+ // 使用该来源的原因 / 为空的解释,展示给用户。
/// Why this source was used (auto mode) or why it is empty.
public string Note { get; set; }
+ // 节点总数(含根)。
public int NodeCount { get; set; }
}
+ // 三来源统一入口;自动模式顺序 UIA→MSAA→Win32。
///
/// Unified entry point for the three tree sources. "Auto" tries UIA, then MSAA, then Win32, and
/// takes the first source that exposes more than just the root node — Win32 is the floor because
@@ -29,18 +54,24 @@ namespace pacs_win_uia.Services
///
public sealed class ControlTreeService
{
+ // UWP/CEF 的内容树异步构建:读到边框后等待这么久再重读一次。
/// How long to wait for an asynchronously built content tree before re-reading.
private const int ChromeContentRetryDelayMs = 700;
+ // UIA 读取器。
private readonly UiAutomationService _uiAutomationService;
+ // MSAA 读取器。
private readonly MsaaTreeReader _msaaTreeReader;
+ // Win32 读取器。
private readonly Win32TreeReader _win32TreeReader;
+ // 默认构造:组装三个默认读取器。
public ControlTreeService()
: this(new UiAutomationService(), new MsaaTreeReader(), new Win32TreeReader())
{
}
+ // 注入三个读取器,便于测试/复用。
public ControlTreeService(
UiAutomationService uiAutomationService,
MsaaTreeReader msaaTreeReader,
@@ -51,6 +82,7 @@ namespace pacs_win_uia.Services
_win32TreeReader = win32TreeReader ?? throw new ArgumentNullException("win32TreeReader");
}
+ // 入口:source 有值走指定来源;否则按 AutoOrder 依次尝试,取首个有内容的来源。
/// Root window.
///
/// Optional UIA root: when the user picked a control inside a window, the UIA tree is read
@@ -107,6 +139,7 @@ namespace pacs_win_uia.Services
return last ?? new ControlTreeResult { Succeeded = false, Note = "没有可用的来源。" };
}
+ // 自动模式的来源优先级。
private static readonly ControlTreeSource[] AutoOrder =
{
ControlTreeSource.Uia,
@@ -114,6 +147,7 @@ namespace pacs_win_uia.Services
ControlTreeSource.Win32
};
+ // 单来源读取:计时、PreparePaths、统计节点、生成说明;跨进程调用都发生在这里。
private ControlTreeResult ReadOne(
IntPtr handle,
AutomationElement uiaRoot,
@@ -155,6 +189,7 @@ namespace pacs_win_uia.Services
};
}
+ // 统一生成绝对 XPath:所有来源读完后都在这里做,保证路径语义一致。
ControlPath.PreparePaths(root);
stopwatch.Stop();
int nodeCount = CountNodes(root);
@@ -188,6 +223,7 @@ namespace pacs_win_uia.Services
};
}
+ // UIA 读取;只在根是窗口句柄时做一次 UWP/浏览器边框重读,重读的始终是同一个窗口。
private ControlTreeNode ReadUia(
IntPtr handle,
AutomationElement uiaRoot,
@@ -224,6 +260,7 @@ namespace pacs_win_uia.Services
return tree;
}
+ // 判断是否“只读到窗口边框”:节点少且有标题栏。
///
/// Few nodes, and a title bar among them: the classic "only the window chrome came back"
/// result of a UWP/CEF top-level window.
@@ -244,6 +281,7 @@ namespace pacs_win_uia.Services
return ContainsControlType(tree, "ControlType.TitleBar");
}
+ // 递归判断树里是否出现某 ControlType。
private static bool ContainsControlType(ControlTreeNode node, string controlType)
{
if (node == null)
@@ -267,6 +305,7 @@ namespace pacs_win_uia.Services
return false;
}
+ // UiaTreeNodeInfo → ControlTreeNode 转换(递归)。
public static ControlTreeNode FromUia(UiaTreeNodeInfo node)
{
if (node == null)
@@ -293,6 +332,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 递归统计节点数(含自身)。
public static int CountNodes(ControlTreeNode node)
{
if (node == null)
@@ -309,6 +349,7 @@ namespace pacs_win_uia.Services
return count;
}
+ // 深度优先找第一个 UIA 节点,供监控编辑器使用。
/// Depth-first search for the first UIA node, used by the monitor editor.
public static UiaElementInfo FindFirstUiaElement(ControlTreeNode node)
{
@@ -334,6 +375,7 @@ namespace pacs_win_uia.Services
return null;
}
+ // 给 UI 下拉框的来源名称列表。
public static IList DescribeSources()
{
return new List { "自动(UIA → MSAA → Win32)", "UIA", "MSAA", "Win32" };
diff --git a/src/pacs_win_uia/Services/ControlValueReader.cs b/src/pacs_win_uia/Services/ControlValueReader.cs
index 099a823..f2643cb 100644
--- a/src/pacs_win_uia/Services/ControlValueReader.cs
+++ b/src/pacs_win_uia/Services/ControlValueReader.cs
@@ -1,3 +1,23 @@
+// ===========================================================================
+// ControlValueReader —— 单个控件的“取值”读取器
+//
+// 职责:按保存的 valueKey 从一个已解析的控件上读取属性/值。编辑器(预填当前值)与无界面
+// 读取器共用同一实现,保证两侧对同一个 key 的含义完全一致。
+// 被谁调用:MainForm(OCR 读取当前控件)、ControlMonitorEditorControl(校验焦点/预填)、
+// HeadlessConfigReader(无界面读取监控项的值)。
+// 读取策略/降级链:先按 node.Source 分派到 UIA / MSAA / Win32 之一;OCR文本 是跨来源兜底键,
+// 仅当对应来源取不到文本、且 OCR 总开关打开时才走截图识别(默认关闭则不调用任何 OCR)。
+// 各来源支持的 valueKey(完整清单见 Models/ControlLocator.cs 的 ControlValueKeys):
+// UIA:Name、AutomationId、ControlType、ClassName、FrameworkId、RuntimeId、IsEnabled、
+// IsOffscreen、BoundingRectangle、Value、Text、选中状态/IsSelected、焦点状态/HasKeyboardFocus。
+// MSAA:accName、accValue、accRole、accState、accDescription、accDefaultAction、PathKey、选中状态、焦点状态。
+// Win32:窗口标题、类名、HWND、窗口矩形、客户区矩形、可见、最小化、进程名、PID、焦点状态。
+// 跨来源键:选中状态(Selected)、焦点状态(Focused)、OCR文本(OcrText);前两者三种来源都接受,OCR 独立于来源。
+// “找不到 ≠ 没有值”:控件存在但该 key 无值,返回的 error 是“控件存在但没有值”,
+// 与“控件找不到/不支持该属性”明确区分。
+// 要改 key 的含义或可用集合:改本文件各 TryRead* 的 switch,以及 ControlValueKeys 清单。
+// ===========================================================================
+
using System;
using System.Collections.Generic;
using System.Windows.Automation;
@@ -18,6 +38,7 @@ namespace pacs_win_uia.Services
/// the provider refused it — "control found but no such property" must stay distinguishable
/// from "control not found".
///
+ // 不支持 OCR 的重载:等价于把 ocr 传 null(此时若 key 为 OCR文本 会返回“未启用”错误)。
public static bool TryRead(ControlTreeNode node, string valueKey, ListReadOptions options, out string value, out string error)
{
return TryRead(node, valueKey, options, null, out value, out error);
@@ -27,6 +48,8 @@ namespace pacs_win_uia.Services
/// Null when OCR is switched off; when present it is the fallback for controls whose text
/// cannot be read through UIA/MSAA/Win32.
///
+ // 主入口:先处理跨来源键 OCR文本,再按 node.Source 分派到 MSAA/Win32/UIA(默认 UIA)。
+ // ocr 为 null 表示 OCR 关闭;开启时它是 UIA/MSAA/Win32 都读不到文本时的兜底取值来源。
public static bool TryRead(
ControlTreeNode node,
string valueKey,
@@ -69,6 +92,7 @@ namespace pacs_win_uia.Services
/// Screenshots the control's rectangle and asks the local OCR service for the text. The value is
/// explicitly OCR-derived: it is not the control's own value and is never presented as one.
///
+ // OCR 取值:截图控件矩形后交本地 OCR 服务识别;结果明确标注为 OCR 派生,不作为控件自身值。
private static bool TryReadByOcr(ControlTreeNode node, OcrReadContext ocr, out string value, out string error)
{
value = null;
@@ -133,6 +157,7 @@ namespace pacs_win_uia.Services
}
/// The tightest rectangle available for a node, whichever source it came from.
+ // 取节点最精确的屏幕矩形:优先 UIA → 其次 MSAA → 最后 Win32 窗口边界(供 OCR 截图用)。
public static NativeRectangleInfo TryGetBounds(ControlTreeNode node)
{
if (node == null)
@@ -153,6 +178,7 @@ namespace pacs_win_uia.Services
return node.Window == null ? null : node.Window.WindowBounds;
}
+ // UIA 取值分派:多数 key 直接读快照属性;Value/Text 走模式、选中状态/焦点状态走各自辅助方法。
private static bool TryReadUia(UiaElementInfo info, string key, ListReadOptions options, out string value, out string error)
{
value = null;
@@ -192,16 +218,20 @@ namespace pacs_win_uia.Services
case "BoundingRectangle":
value = info.BoundingRectangle == null ? null : info.BoundingRectangle.ToString();
break;
+ // Value/Text 需要实时的模式调用,不支持就报错。
case "Value":
case "Text":
return TryReadUiaPatternValue(info, key, options, out value, out error);
+ // 选中状态:支持“选中状态”(Selected) 与 “IsSelected” 两个别名。
case ControlValueKeys.Selected:
case "IsSelected":
return TryReadUiaSelected(info, key, out value, out error);
+ // 焦点状态:支持“焦点状态”(Focused) 与 “HasKeyboardFocus” 两个别名。
case ControlValueKeys.Focused:
case "HasKeyboardFocus":
return TryReadUiaFocus(info, key, out value, out error);
default:
+ // 未知 key:报错并列出该来源可用 key。
error = "UIA 不支持的属性名:" + key + ";可用:" + string.Join(",", ControlValueKeys.Uia);
return false;
}
@@ -216,6 +246,7 @@ namespace pacs_win_uia.Services
}
/// Value/Text need live pattern calls, so they are only attempted when asked for.
+ // Value/Text 需要实时模式调用,仅在明确请求时才尝试:Value 用 ValuePattern,Text 用 TextPattern(按 MaxTextLength 有界读取)。
private static bool TryReadUiaPatternValue(UiaElementInfo info, string key, ListReadOptions options, out string value, out string error)
{
value = null;
@@ -265,6 +296,7 @@ namespace pacs_win_uia.Services
}
/// Whether this element is the selected one; needs SelectionItemPattern.
+ // 选中状态:需 SelectionItemPattern(列表行/项通常支持);IsSelected 别名返回 True/False,否则返回“是/否”。
private static bool TryReadUiaSelected(UiaElementInfo info, string key, out string value, out string error)
{
value = null;
@@ -297,6 +329,7 @@ namespace pacs_win_uia.Services
}
}
+ // MSAA 选中状态:从 accState 文本推断(含“已选中”即为是,“有焦点”则是有焦点但未选中)。
private static string DescribeMsaaSelection(MsaaNodeInfo info)
{
string state = info.StateText ?? string.Empty;
@@ -309,6 +342,7 @@ namespace pacs_win_uia.Services
}
/// Whether the element has keyboard focus; UIA exposes this as a plain property.
+ // 焦点状态:UIA 直接暴露 HasKeyboardFocus 属性;HasKeyboardFocus 别名返回 True/False,否则返回中文描述。
private static bool TryReadUiaFocus(UiaElementInfo info, string key, out string value, out string error)
{
value = null;
@@ -338,6 +372,7 @@ namespace pacs_win_uia.Services
return true;
}
+ // MSAA 焦点状态:从 accState 文本里是否含“有焦点”推断。
private static string DescribeMsaaFocus(MsaaNodeInfo info)
{
string state = info.StateText ?? string.Empty;
@@ -348,6 +383,7 @@ namespace pacs_win_uia.Services
/// Win32 has no per-window "is focused" flag exposed to other processes: focus is a property
/// of the thread's message queue, so this compares against the foreground window.
///
+ // Win32 焦点状态:Win32 没有跨进程的“是否聚焦”标志(焦点属于线程消息队列),故与前台窗口比较判定。
private static bool TryReadWin32Focus(NativeWindowInfo info, out string value, out string error)
{
value = null;
@@ -371,6 +407,8 @@ namespace pacs_win_uia.Services
}
}
+ // MSAA 取值分派:accName/accValue/accRole/accState/accDescription/accDefaultAction/PathKey,
+ // 以及跨来源键“选中状态”“焦点状态”(由状态文本推断)。
private static bool TryReadMsaa(MsaaNodeInfo info, string key, out string value, out string error)
{
value = null;
@@ -424,6 +462,7 @@ namespace pacs_win_uia.Services
return true;
}
+ // Win32 取值分派:窗口标题/类名/HWND/窗口矩形/客户区矩形/可见/最小化/进程名/PID,以及跨来源键“焦点状态”。
private static bool TryReadWin32(NativeWindowInfo info, string key, out string value, out string error)
{
value = null;
diff --git a/src/pacs_win_uia/Services/FloatingBarManager.cs b/src/pacs_win_uia/Services/FloatingBarManager.cs
index f3eccea..816edb9 100644
--- a/src/pacs_win_uia/Services/FloatingBarManager.cs
+++ b/src/pacs_win_uia/Services/FloatingBarManager.cs
@@ -1,3 +1,34 @@
+// ============================================================================
+// FloatingBarManager —— “悬浮条”(独立操作条,方案 B)的总调度器
+//
+// 职责:
+// 按用户配置的显示条件决定每个悬浮条何时出现;出现后把它用“相对偏移”粘在锚定窗口上;
+// 并负责注册/注销可选的全局快捷键。
+//
+// 被谁调用:
+// MainForm(宿主窗口)持有实例:settings(读取设置)、owner(RegisterHotKey 的宿主窗口)、
+// actionHandler(按钮被点/快捷键触发后真正执行动作的回调)。owner 的 WndProc 收到 WM_HOTKEY
+// 时调用 HandleHotkey。设置页用静态的 CheckDisplayConditions 做“显示条件自检”。
+//
+// 节拍与线程:
+// · UI 线程:一个 300ms(可配置,DefaultRefreshIntervalMs)的 WinForms Timer 取锚定窗口矩形、
+// 移动/显示悬浮条、消费后台结果。这里只做廉价 Win32 调用(GetWindowRect/IsWindow 等),
+// 绝不在这里做 Capture/EnumWindows/UIA。
+// · 后台线程:窗口枚举 + path 定位(可能阻塞在其他进程)在 Task 里“单飞”批处理,一次一批;
+// 批处理没跑完就跳过本拍、不排队。完成后的结果由 UI 线程一拍取走(单个结果槽,不刷回调)。
+// · generation(配置代号):每次 Reload 递增;回填结果前比对代号,过期结果直接丢弃,
+// 避免旧配置的后台结果影响新配置。
+//
+// 不抢焦点/点击穿透:
+// 悬浮条窗口使用 WS_EX_NOACTIVATE|WS_EX_TOOLWINDOW,ShowWithoutActivation=true,
+// 圆角外空白由 WM_NCHITTEST 返回 HTTRANSPARENT 穿透(详见 FloatingToolbarForm),键盘始终留给 PACS。
+//
+// “要改什么就改哪里”:
+// · 显示条件判定与诊断文案 → EvaluateDisplay / IsAnchorVisible / FindConditionWindow
+// · 后台批处理与单飞 → OnTick / CheckBars
+// · 跟随与拖动回写 → FollowBar / ComputeLocation
+// · 快捷键 → Reload / HandleHotkey / UnregisterHotkeys
+// ============================================================================
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -11,6 +42,7 @@ using pacs_win_uia.UI;
namespace pacs_win_uia.Services
{
+ /// 悬浮条动作事件参数:哪个条(Bar)的哪个按钮(Button)被触发。
public sealed class FloatingActionEventArgs2 : EventArgs
{
public FloatingActionEventArgs2(FloatingBarDefinition bar, FloatingButtonDefinition button)
@@ -19,20 +51,28 @@ namespace pacs_win_uia.Services
Button = button;
}
+ /// 触发的悬浮条定义。
public FloatingBarDefinition Bar { get; private set; }
+ /// 被触发的按钮定义(用对象引用匹配,避免同名按钮误触)。
public FloatingButtonDefinition Button { get; private set; }
}
/// A read-only snapshot, shared by runtime checks and the settings diagnostic.
public sealed class FloatingBarDisplayCheck
{
+ /// 是否满足显示条件。
public bool CanShow { get; internal set; }
+ /// 不满足时的原因 / 满足时的说明(展示给用户)。
public string Reason { get; internal set; }
+ /// 判定出的锚定窗口句柄。
public IntPtr Anchor { get; internal set; }
+ /// 导入 XPath 条件对应的窗口句柄(无导入条件时为 0)。
public IntPtr ConditionAnchor { get; internal set; }
+ /// 附加详情(锚定窗口、PID、XPath 定位步骤等)。
public string Details { get; internal set; }
+ /// 渲染成“满足/不显示:原因 + 详情”的多行文本。
public override string ToString()
{
return (CanShow ? "当前满足显示条件:" : "当前不显示:") + Reason
@@ -50,17 +90,28 @@ namespace pacs_win_uia.Services
///
public sealed class FloatingBarManager : IDisposable
{
+ /// 读取当前 AppSettings 的委托(设置页保存后可即时生效)。
private readonly Func _settings;
+ /// RegisterHotKey 使用的宿主窗口句柄。
private readonly Control _owner;
+ /// 按钮被点/快捷键触发后的动作回调(真正执行动作的入口)。
private readonly EventHandler _actionHandler;
+ /// UI 线程节拍器:默认 300ms,只做廉价取矩形与跟随。
private readonly System.Windows.Forms.Timer _timer;
+ /// 当前启用的悬浮条运行时列表(UI 线程读写)。
private readonly List _bars = new List();
+ /// 已成功注册的全局快捷键。
private readonly List _hotkeys = new List();
+ /// 本进程 PID:用于把本工具自身窗口排除出“遮挡者”。
private readonly int _ownProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;
+ /// 后台批处理“单飞”任务;非空表示有一批在跑,跑完前不再起新的。
private Task _checkTask;
+ /// 配置代号:Reload 时递增,过期的后台结果按代丢弃。
private int _generation;
+ /// 是否已释放。
private bool _disposed;
+ /// 绑定设置读取、宿主窗口与动作回调,并建立 300ms 节拍器。
public FloatingBarManager(
Func settings,
Control owner,
@@ -73,43 +124,68 @@ namespace pacs_win_uia.Services
_timer.Tick += OnTick;
}
+ /// 一条悬浮条的运行时状态(仅 UI 线程读写)。
private sealed class BarRuntime
{
+ /// 该条的配置定义。
internal FloatingBarDefinition Definition;
+ /// 已创建的悬浮条窗体(懒创建)。
internal FloatingToolbarForm Form;
+ /// 锚定窗口句柄(由后台批处理结果回填)。
internal IntPtr Anchor = IntPtr.Zero;
+ /// 导入 XPath 条件对应的窗口句柄。
internal IntPtr ConditionAnchor;
+ /// 上一批判定:进程/类/标题(+导入 XPath)是否同时满足。
internal bool ControlConditionOk;
+ /// 刚结束一次拖动:下一拍要把新位置回写成相对偏移。
internal bool WasDragging;
+ /// 上次状态文案,变化时才写日志,避免刷屏。
internal string LastStatus;
}
+ /// 派给后台批处理的一次检查请求(含发起时的配置代号)。
private sealed class BarCheckRequest
{
+ /// 对应的运行时条目。
internal BarRuntime Runtime;
+ /// 本拍已知的锚定窗口句柄。
internal IntPtr Anchor;
+ /// 本拍已知的 XPath 条件窗口句柄。
internal IntPtr ConditionAnchor;
+ /// 发起时的配置代号,用于回填前判过期。
internal int Generation;
}
+ /// 后台批处理的一项结果(由 UI 线程消费)。
private sealed class BarCheckResult
{
+ /// 对应的请求(含运行时与配置代号)。
internal BarCheckRequest Request;
+ /// 判定出的锚定窗口句柄。
internal IntPtr Anchor;
+ /// 判定出的 XPath 条件窗口句柄。
internal IntPtr ConditionAnchor;
+ /// 是否满足全部显示条件。
internal bool ConditionOk;
+ /// 人类可读的状态/原因,用于日志与诊断。
internal string Reason;
}
+ /// 一条已注册的全局快捷键。
private sealed class HotkeyRegistration
{
+ /// RegisterHotKey 使用的 id。
internal int Id;
+ /// 所属悬浮条。
internal FloatingBarDefinition Bar;
+ /// 被触发的按钮。
internal FloatingButtonDefinition Button;
+ /// 快捷键文本(仅用于日志)。
internal string Shortcut;
}
/// Rebuilds the bars and hotkeys from the current settings.
+ /// 按当前设置重建悬浮条与快捷键:先拆掉旧窗体/快捷键,再按新配置创建(不清 _checkTask)。
public void Reload()
{
if (_disposed)
@@ -199,6 +275,7 @@ namespace pacs_win_uia.Services
}
/// Called from the owner's WndProc when a registered hotkey fires.
+ /// 宿主窗口收到 WM_HOTKEY 时调用:命中已注册 id 则触发对应按钮并返回 true。
public bool HandleHotkey(int id)
{
foreach (HotkeyRegistration registration in _hotkeys)
@@ -216,6 +293,7 @@ namespace pacs_win_uia.Services
return false;
}
+ /// 注销全部已注册快捷键(失败按尽力而为处理)并清空列表。
private void UnregisterHotkeys()
{
foreach (HotkeyRegistration registration in _hotkeys)
@@ -233,6 +311,7 @@ namespace pacs_win_uia.Services
_hotkeys.Clear();
}
+ /// 取当前设置的刷新间隔(毫秒,已归一化);供节拍器和 Reload 使用。
private int GetRefreshIntervalMs()
{
AppSettings settings = _settings();
@@ -240,6 +319,7 @@ namespace pacs_win_uia.Services
settings == null || settings.FloatingButton == null ? 0 : settings.FloatingButton.RefreshIntervalMs);
}
+ /// UI 线程一拍:先消费上批结果(按 generation 判过期),再逐个跟随/显示,最后按需发起新批处理。
private void OnTick(object sender, EventArgs e)
{
if (_disposed || _owner.IsDisposed)
@@ -317,6 +397,7 @@ namespace pacs_win_uia.Services
}
}
+ /// 按相对偏移把悬浮条跟随锚定窗口;拖动中交给鼠标、不抢位置;拖动结束后回写新偏移。
private void FollowBar(BarRuntime runtime)
{
FloatingToolbarForm form = runtime.Form;
@@ -370,6 +451,7 @@ namespace pacs_win_uia.Services
}
}
+ /// 运行时的廉价更新:只用 Win32 取锚定窗口矩形与可见性,决定显示还是隐藏。
private void UpdateBar(BarRuntime runtime)
{
// No Capture/EnumWindows/UIA here: position and visibility use cheap Win32 calls only.
@@ -402,6 +484,7 @@ namespace pacs_win_uia.Services
Show(runtime, anchor);
}
+ /// 后台单次批处理:只做一次窗口枚举,再逐个判定;配置代号一变立即中止。
private BarCheckResult[] CheckBars(IList requests)
{
// One discovery per batch; all provider work remains off the UI thread.
@@ -434,6 +517,7 @@ namespace pacs_win_uia.Services
return EvaluateDisplay(bar, ref windows);
}
+ /// 核心判定:进程/类/标题(+导入 XPath)必须同时满足且唯一命中,才允许显示;windows 可跨条复用。
private static FloatingBarDisplayCheck EvaluateDisplay(FloatingBarDefinition bar,
ref IList windows)
{
@@ -514,6 +598,7 @@ namespace pacs_win_uia.Services
return result;
}
+ /// 进程名/窗口类/标题三者是否至少填了一个(三者是“与”关系,不是兜底查找)。
public static bool HasWindowConditions(string process, string windowClass, string title)
{
return !string.IsNullOrWhiteSpace(process) || !string.IsNullOrWhiteSpace(windowClass)
@@ -521,6 +606,8 @@ namespace pacs_win_uia.Services
}
/// Display predicates are AND conditions, not a best-effort locator fallback.
+ /// 在候选窗口里找“同时满足进程+类+标题”的窗口:
+ /// 优先选可见窗口(跳过最小化的同名框架窗口),只有唯一命中才返回,多个则要求补充条件。
public static NativeWindowInfo FindConditionWindow(IList windows, string process,
string windowClass, string title, out string error)
{
@@ -611,6 +698,7 @@ namespace pacs_win_uia.Services
using (visible)
{
+ // 只要还剩哪怕一点可见面积,就认为“没被完全遮住”(不要求整块无遮挡)。
if (WindowVisibility.HasArea(visible)) return true;
}
@@ -618,6 +706,7 @@ namespace pacs_win_uia.Services
return false;
}
+ /// 把 System.Drawing.Rectangle 转成 Win32 风格的原生矩形信息。
private static NativeRectangleInfo ToNativeRectangle(Rectangle rectangle)
{
return new NativeRectangleInfo
@@ -626,6 +715,7 @@ namespace pacs_win_uia.Services
};
}
+ /// 把候选窗口渲染成最多 4 行文本,附在“不能确定锚点”的错误后面。
private static string DescribeCandidates(IList windows)
{
var text = new System.Text.StringBuilder();
@@ -637,6 +727,7 @@ namespace pacs_win_uia.Services
return text.ToString();
}
+ /// 去空白并去掉结尾的 .exe,便于进程名比较。
public static string NormalizeProcessName(string process)
{
process = (process ?? string.Empty).Trim();
@@ -644,6 +735,7 @@ namespace pacs_win_uia.Services
? process.Substring(0, process.Length - 4) : process;
}
+ /// 懒创建窗体并显示在计算出的位置(位置统一走 ComputeLocation,与 FollowBar 一致)。
private void Show(BarRuntime runtime, Rectangle anchor)
{
if (runtime.Form == null)
@@ -675,6 +767,7 @@ namespace pacs_win_uia.Services
/// the working area it belongs to. Used by both the condition tick and the follow tick, so the
/// bar cannot be "correct" in one and jump somewhere else in the other.
///
+ /// 锚定窗口左上角 + 配置的相对偏移,并夹取在工作区内,保证不跑出屏幕。
private static Point ComputeLocation(FloatingBarDefinition bar, Size size, Rectangle anchor)
{
var target = new Rectangle(
@@ -707,6 +800,7 @@ namespace pacs_win_uia.Services
return target.Location;
}
+ /// 隐藏该条的窗体(若已创建且当前可见)。
private void Hide(BarRuntime runtime)
{
if (runtime.Form != null && runtime.Form.Visible)
@@ -715,6 +809,7 @@ namespace pacs_win_uia.Services
}
}
+ /// 窗体按钮被点击后的回调:先按窗体对象引用定位条目,再用按钮定义引用(而非显示名)匹配。
private void OnBarActionInvoked(object sender, FloatingActionEventArgs e)
{
var form = sender as FloatingToolbarForm;
@@ -744,6 +839,7 @@ namespace pacs_win_uia.Services
}
}
+ /// 触发动作回调(button 为空直接忽略)。
private void Invoke(FloatingBarDefinition bar, FloatingButtonDefinition button)
{
if (button == null)
@@ -758,6 +854,7 @@ namespace pacs_win_uia.Services
}
}
+ /// 释放:递增代号(作废在飞的后台结果)、停表、注销快捷键、销毁全部窗体。
public void Dispose()
{
if (_disposed)
diff --git a/src/pacs_win_uia/Services/HeadlessConfigReader.cs b/src/pacs_win_uia/Services/HeadlessConfigReader.cs
index def3037..dbb8fe5 100644
--- a/src/pacs_win_uia/Services/HeadlessConfigReader.cs
+++ b/src/pacs_win_uia/Services/HeadlessConfigReader.cs
@@ -5,6 +5,25 @@ using System.Threading;
using pacs_win_uia.Diagnostics;
using pacs_win_uia.Models;
+// ============================================================================
+// HeadlessConfigReader.cs —— 无界面(headless)读取已保存的监控配置
+// 职责:不弹任何 UI,跑一遍保存的监控配置,报告哪些控件读到了、值是什么。
+// 被谁调用:无界面 / 命令行模式的入口(读配置后用 HeadlessReport 输出 JSON)。
+// 核心原则 —— 绝不伪造数据:定位不到就报“未定位”;定位到但取值失败报 Found=true、ValueAvailable=false
+// 并带上原因;只有 ValueKey 为空(仅定位)的条目才不取值。绝不编造值。
+// 每条独立计时:单条 ElapsedMs 记录该条目从等窗口到取值的总耗时;条目自带的 TimeoutSeconds
+// 优先于全局 --timeout。
+// 统计口径(Summary):Total=定义总数;Skipped=停用且被跳过;Missing=未定位到;
+// ValueUnavailable=定位到但取不到值(仅指设了 ValueKey 的条目);Found=定位到且值可用,
+// 以及未设 ValueKey 的“仅定位”条目也计入 Found。
+// OCR:只有传入的 OcrReadContext 非空(表示 OCR 已打开)时,才在取值失败后降级到 OCR;降级成功的值会计入
+// 并标注来自 OCR(不是控件原生值)。
+// 要改什么就改哪里:
+// - 统计口径:Read 结尾的 Summary 汇总循环。
+// - 单条流程 / 超时 / OCR 降级:ReadItem。
+// - 等窗口逻辑:WaitForWindow 与 WindowPollIntervalMs。
+// - 控件属性导出:BuildAttributes。
+// ============================================================================
namespace pacs_win_uia.Services
{
///
@@ -16,20 +35,26 @@ namespace pacs_win_uia.Services
///
public sealed class HeadlessConfigReader
{
+ // 监控配置的读取存储。
private readonly ControlMonitorStore _store;
+ // 控件定位服务(找窗口 + 解析控件路径)。
private readonly ControlLocatorService _locatorService;
+ // 只读的窗口枚举/快照服务。
private readonly NativeWindowService _windowService;
+ // 默认构造:使用真实的配置存储、定位服务与窗口服务。
public HeadlessConfigReader()
: this(new ControlMonitorStore(), new ControlLocatorService(), new NativeWindowService())
{
}
+ // 只替换配置存储(测试/定制场景),其余仍用默认实现。
public HeadlessConfigReader(ControlMonitorStore store)
: this(store, new ControlLocatorService(), new NativeWindowService())
{
}
+ // 全量注入:依赖为空即抛 ArgumentNullException。
public HeadlessConfigReader(
ControlMonitorStore store,
ControlLocatorService locatorService,
@@ -43,6 +68,7 @@ namespace pacs_win_uia.Services
/// How long to keep waiting for a target window to appear.
/// Ask targets to switch their accessibility support on first.
/// OCR fallback context, or null when OCR is off (the default).
+ /// 便捷重载:默认跳过已停用的条目(skipDisabled=true)。
public HeadlessReport Read(
string configPath,
TimeSpan windowTimeout,
@@ -53,6 +79,8 @@ namespace pacs_win_uia.Services
return Read(configPath, windowTimeout, activate, ocr, cancellationToken, true);
}
+ // 主流程:加载配置 → 枚举顶层窗口(作为诊断用搜索空间)→ 逐条读取 → 汇总统计。
+ // activate 为真时先建无障碍激活服务并在结束时释放;cancellationToken 在每条之间检查取消。
public HeadlessReport Read(
string configPath,
TimeSpan windowTimeout,
@@ -133,6 +161,7 @@ namespace pacs_win_uia.Services
return report;
}
+ // 读取单条定义:等窗口 → (可选)激活无障碍 → 定位控件 → 取值 → (可选)OCR 降级,全程写入 steps 诊断轨迹。
private HeadlessItemResult ReadItem(
ControlMonitorDefinition definition,
TimeSpan windowTimeout,
@@ -245,8 +274,10 @@ namespace pacs_win_uia.Services
return item;
}
+ // 触发无障碍激活后阻塞等待的毫秒数,留时间让目标把无障碍树建起来。
private const int BlockingActivationWaitMs = 800;
+ // 轮询等待目标顶层窗口出现,直到超时或取消;返回找得到的窗口句柄,找不到返回 IntPtr.Zero。
private IntPtr WaitForWindow(
ControlMonitorDefinition definition,
TimeSpan windowTimeout,
@@ -282,8 +313,10 @@ namespace pacs_win_uia.Services
return IntPtr.Zero;
}
+ // 等窗口的轮询间隔(500ms)。
private const int WindowPollIntervalMs = 500;
+ // 按控件节点来源(MSAA/Win32/UIA)导出对应的只读属性快照,供报告展示。
private static HeadlessAttributes BuildAttributes(ControlTreeNode node)
{
if (node == null)
diff --git a/src/pacs_win_uia/Services/HighlightFollower.cs b/src/pacs_win_uia/Services/HighlightFollower.cs
index cbb0e49..f7bb7bf 100644
--- a/src/pacs_win_uia/Services/HighlightFollower.cs
+++ b/src/pacs_win_uia/Services/HighlightFollower.cs
@@ -1,3 +1,28 @@
+// ============================================================================
+// HighlightFollower —— 让一个高亮矩形“粘”在目标控件上的跟随器
+//
+// 职责:
+// 把高亮框跟随目标控件;一旦目标消失/被完全遮挡/最小化,就把框撤下,并且只上报一次原因。
+//
+// 被谁调用:
+// 上层(MainForm/监控)在选中控件后调用 Show(...);Hidden 事件用于更新状态栏文案;
+// Dispose 由持有者负责。
+//
+// 节拍与线程:
+// · 快路径(UI 线程,120ms 定时器,FollowIntervalMs):纯 Win32。控件在顶层窗口内的偏移只在
+// Show/重新解析时量一次,之后每拍只重读该窗口的 GetWindowRect(内核应答,绝不会卡在目标进程),
+// 所以 120ms 也安全(比“松手后才跳位置”的旧体验好)。
+// · 慢路径(后台线程,单飞):UIA/MSAA/Win32 重新定位可能阻塞,按 ReResolveIntervalMs 运行,
+// 用 _resolutionInFlight 保证不重叠;结果回 UI 线程后再纠正偏移(用于捕捉滚动/布局变化,
+// 而不是窗口移动)。会话号 _session 用于丢弃过期结果。
+//
+// 不抢焦点/点击穿透:高亮框窗体(HighlightOverlayForm)本身置顶、NOACTIVATE、点击穿透。
+//
+// “要改什么就改哪里”:
+// · 跟随节拍与可见性判定 → Tick / FollowIntervalMs
+// · 后台重新解析与单飞 → MaybeReResolve / ApplyReResolved / SetReResolveIntervalMs
+// · 偏移计算 → UpdateOffset;停止/隐藏 → StopCore / StopAndNotify
+// ============================================================================
using System;
using System.Drawing;
using System.Threading;
@@ -10,6 +35,7 @@ using pacs_win_uia.UI;
namespace pacs_win_uia.Services
{
+ /// 高亮框被隐藏的事件参数(携带原因)。
public sealed class HighlightHiddenEventArgs : EventArgs
{
public HighlightHiddenEventArgs(string reason)
@@ -18,6 +44,7 @@ namespace pacs_win_uia.Services
}
/// Why the box is no longer drawn; shown in the status bar.
+ /// 不再绘制的原因,显示在状态栏。
public string Reason { get; private set; }
}
@@ -35,27 +62,47 @@ namespace pacs_win_uia.Services
///
public sealed class HighlightFollower : IDisposable
{
+ /// 快路径跟随周期(毫秒)。
private const int FollowIntervalMs = 120;
+ /// 真正负责画框的窗体重用实例。
private readonly HighlightOverlayForm _overlay;
+ /// UI 线程 120ms 跟随定时器。
private readonly System.Windows.Forms.Timer _timer;
+ /// 本进程 PID,供可见性判定排除自身窗口。
private readonly int _ownProcessId;
+ /// 可选:后台重新定位委托,返回控件新的屏幕矩形。
private Func _reResolve;
+ /// 锚定顶层窗口句柄。
private IntPtr _anchor = IntPtr.Zero;
+ /// 最近已知的控件屏幕矩形。
private Rectangle _bounds;
+ /// 控件尺寸;跟随只做平移,尺寸变化由重新解析更新。
private Size _size;
+ /// 控件相对锚定窗口左上角的 X 偏移。
private int _offsetX;
+ /// 控件相对锚定窗口左上角的 Y 偏移。
private int _offsetY;
+ /// 高亮框名称(拼进隐藏提示文案)。
private string _label;
+ /// 后台重新解析周期(毫秒)。
private int _reResolveIntervalMs = AppSettings.DefaultRefreshIntervalMs;
+ /// 下次允许重新解析的时间(UTC)。
private DateTime _nextReResolveUtc;
+ /// 会话号:每次 Show/Stop 递增,用于丢弃过期结果。
private int _session;
+ /// 是否正在跟踪目标(不一定当前可见)。
private bool _active;
+ /// 高亮框当前是否已显示。
private bool _shown;
+ /// 本次隐藏是否已上报,避免重复通知。
private bool _hiddenReported;
+ /// 后台重新解析是否在进行(单飞闸门,volatile)。
private volatile bool _resolutionInFlight;
+ /// 是否已释放。
private bool _disposed;
+ /// 建立跟随器:记录自身 PID、创建高亮窗体并启动 120ms 节拍器。
public HighlightFollower(int ownProcessId)
{
_ownProcessId = ownProcessId;
@@ -65,26 +112,31 @@ namespace pacs_win_uia.Services
}
/// Raised once when the box stops being drawn because the target disappeared or is covered.
+ /// 目标消失或被完全遮挡导致框不再绘制时,触发一次。
public event EventHandler Hidden;
/// True while a target is being followed (not necessarily currently visible).
+ /// 是否正在跟踪目标(不代表此刻可见)。
public bool IsTracking
{
get { return _active; }
}
/// True while the box is actually on screen.
+ /// 高亮框此刻是否真的在屏幕上。
public bool IsVisible
{
get { return _active && _shown && _overlay.Visible; }
}
+ /// 当前锚定的顶层窗口句柄。
public IntPtr AnchorWindow
{
get { return _anchor; }
}
/// Interval used for potentially blocking UIA/MSAA re-resolution.
+ /// 可能阻塞的后台重新解析所用周期(毫秒)。
public int ReResolveIntervalMs
{
get { return _reResolveIntervalMs; }
@@ -94,6 +146,7 @@ namespace pacs_win_uia.Services
/// Sets the background re-resolution cadence. Win32 position following remains at 120 ms;
/// this value only controls the potentially blocking resolver.
///
+ /// 设置后台重新解析周期;Win32 位置跟随仍是 120ms,本值只影响可能阻塞的解析器。
public void SetReResolveIntervalMs(int intervalMs)
{
_reResolveIntervalMs = AppSettings.NormalizeRefreshIntervalMs(intervalMs);
@@ -105,6 +158,7 @@ namespace pacs_win_uia.Services
/// keeps it relative to . is
/// optional: it is called on a background thread at ReResolveIntervalMs to correct the offset.
///
+ /// 开始跟随:记录矩形/锚定窗口/标签与可选解析器,量一次偏移后立即跑一拍。
public void Show(Rectangle controlBounds, IntPtr anchorWindow, Func reResolve, string label)
{
if (_disposed)
@@ -134,16 +188,19 @@ namespace pacs_win_uia.Services
}
/// Stops following and hides the box. No event: the caller asked.
+ /// 停止跟随并隐藏(调用方主动要求,因此不触发 Hidden 事件)。
public void Hide(string reason)
{
StopCore(false);
}
+ /// 120ms 定时器回调,转发到 Tick。
private void OnTimerTick(object sender, EventArgs e)
{
Tick();
}
+ /// 快路径一拍:只读锚定窗口矩形 + 可见性,决定移动/隐藏高亮框;必要时触发后台解析。
private void Tick()
{
if (_disposed || !_active)
@@ -209,6 +266,7 @@ namespace pacs_win_uia.Services
MaybeReResolve();
}
+ /// 到点且无在飞解析时,启动一次后台重新定位(单飞;结果回 UI 线程再应用)。
private void MaybeReResolve()
{
if (_reResolve == null || _resolutionInFlight)
@@ -287,6 +345,7 @@ namespace pacs_win_uia.Services
TaskScheduler.Default);
}
+ /// 在 UI 线程应用后台解析结果:会话过期则丢弃;控件已消失则停止并上报。
private void ApplyReResolved(int session, Rectangle? result)
{
if (_disposed || !_active || session != _session)
@@ -307,6 +366,7 @@ namespace pacs_win_uia.Services
}
/// Measures where the control sits inside the anchor window, once per new rectangle.
+ /// 量出控件相对锚定窗口左上角的偏移(每个新矩形量一次)。
private void UpdateOffset()
{
_offsetX = _bounds.Left;
@@ -324,6 +384,7 @@ namespace pacs_win_uia.Services
}
}
+ /// 用 GetWindowRect 取窗口屏幕矩形;无效或零尺寸返回 false。
private static bool TryGetWindowRectangle(IntPtr handle, out Rectangle rectangle)
{
rectangle = Rectangle.Empty;
@@ -338,16 +399,19 @@ namespace pacs_win_uia.Services
return rectangle.Width > 0 && rectangle.Height > 0;
}
+ /// 停止并上报隐藏原因。
private void StopAndNotify(string reason)
{
StopCore(true, reason);
}
+ /// 停止且不上报(内部复用)。
private void StopCore(bool notify)
{
StopCore(notify, null);
}
+ /// 停止核心:停表、清状态、递增会话号作废在飞结果、隐藏框,按需触发 Hidden。
private void StopCore(bool notify, string reason)
{
_timer.Stop();
@@ -365,6 +429,7 @@ namespace pacs_win_uia.Services
}
}
+ /// 触发 Hidden 事件(携带原因)。
private void Notify(string reason)
{
EventHandler handler = Hidden;
@@ -374,6 +439,7 @@ namespace pacs_win_uia.Services
}
}
+ /// 释放:停表、解绑并销毁定时器,销毁高亮窗体。
public void Dispose()
{
if (_disposed)
diff --git a/src/pacs_win_uia/Services/ListReaderService.cs b/src/pacs_win_uia/Services/ListReaderService.cs
index 4c8ce59..cc6765b 100644
--- a/src/pacs_win_uia/Services/ListReaderService.cs
+++ b/src/pacs_win_uia/Services/ListReaderService.cs
@@ -1,3 +1,41 @@
+// ===========================================================================
+// ListReaderService —— 列表读取服务(只读)
+//
+// 职责:
+// 从 UI Automation(UIA)树里,把“被拾取元素”附近的一个列表/表格读成结构化的
+// 行、列、单元格与选中项。只读取标准 UIA 模式暴露的数据,绝不调用 Select/Invoke/
+// ValuePattern.SetValue 等会改变目标状态的写操作。
+//
+// 被谁调用:
+// MainForm 的「读取选中控件列表」菜单项,以及悬浮按钮条的 ReadList 动作
+// (见 MainForm.ReadList)。目前没有无界面(headless)的列表读取入口。
+//
+// 读取策略顺序(从强到弱、先精确后降级):
+// 1) TablePattern(带语义行列标识)→ 2) GridPattern(行列计数 + 单元格)
+// → 3) 在“被拾取元素”内部向下找列表(BFS,ReadDescendants)
+// → 4) 沿“被拾取元素 + 其上级”向上做遍历降级读(ReadTraversalChain)
+// → 5) 在被拾取元素内部向下做遍历降级读(ReadDescendantTraversal)。
+// 本服务只覆盖 UIA;MSAA / Win32 / OCR 属于“单个控件取值”场景,见 ControlValueReader,
+// 列表读取不涉及它们。
+// 注意:所有模式探测一定先于任何遍历——遍历几乎总能“找到”东西(窗口里的布局面板
+// 看起来就像行),所以绝不允许它抢占真正存在的 GridPattern/TablePattern。
+//
+// “找不到 ≠ 空列表”:
+// 读不到时返回 Status=Unsupported/Failed 并带 Error,绝不返回一个“0 行”的成功结果
+// 来冒充空列表;Provider 不支持 ≠ 列表没有数据。
+//
+// 预算与超时(软截止):
+// 同步的 Provider 调用无法在进程内被强制中断,所以 Timeout 是“软截止”——只在每个
+// 可打断的检查点(ThrowIfStopped / TraversalState.Spend)生效。另有节点预算
+// MaxTraversalNodes、深度预算 MaxTraversalDepth/MaxAncestorDepth、行/列上限
+// MaxRows/MaxColumns、错误上限 MaxErrors 与连续失败熔断共同兜底。
+//
+// 要改读取优先级就改哪个方法:
+// 改“先试哪个来源/模式”的顺序 → Read();改 Table/Grid 的探测先后 → TryReadPatterns;
+// 改向上遍历的取舍规则 → ReadTraversalChain;改向下查找/遍历 → ReadDescendants /
+// ReadDescendantTraversal;改“哪些控件类不可能是列表” → IsControlNotContainer。
+// ===========================================================================
+
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -23,16 +61,22 @@ namespace pacs_win_uia.Services
public sealed class ListReaderService
{
/// UIA_DesktopControlTypeId; the root element type on providers that report it.
+ // 桌面根元素类型(UIA_DesktopControlTypeId);IsDesktop 用它识别根,禁止越过桌面上下遍历。
private const int DesktopControlTypeId = 50016;
/// Stop reading cells after this many consecutive failures with no success at all.
+ // 连续失败熔断阈值:从未成功过的 Provider 连续这么多单元格失败后即停,避免逐格挨个报错。
private const int MaxConsecutiveCellFailures = 10;
/// How deep and how wide the downward search for a list inside the picked element goes.
+ // 向下查找列表的层数上限(相对被拾取元素向下最多几层)。
private const int DescendantDepth = 4;
+ // 向下查找(BFS)访问节点的总预算,超出即停止。
private const int DescendantNodeBudget = 600;
+ // 向下“遍历降级”尝试读取的次数上限。
private const int MaxDescendantTraversalAttempts = 25;
+ // 读取入口:按候选链依次尝试 模式探测 → 向下查找 → 向上遍历 → 向下遍历,最终返回结构化结果。
public ListReadResult Read(AutomationElement element, ListReadOptions options, CancellationToken cancellationToken)
{
if (options == null)
@@ -154,16 +198,25 @@ namespace pacs_win_uia.Services
}
}
+ // 一个候选元素:来自被拾取元素本身、其上级祖先,或其后代(向下查找得到)。
private struct ReadCandidate
{
+ // 该候选对应的 UIA 元素引用。
internal AutomationElement Element;
+ // 相对被拾取元素的层数:>0 为上级;来自后代时由调用处以负数表示。
internal int Level;
+ // 候选元素名称(快照,读取失败时为 null)。
internal string Name;
+ // 候选元素的控件类型名(如 ControlType.DataItem)。
internal string ControlType;
+ // 是否为顶层窗口(是则不再向上:再往上就是桌面)。
internal bool IsTopLevelWindow;
+ // true 表示该候选来自被拾取元素的后代(向下查找得到)。
internal bool FromDescendant;
+ // 关联的原生窗口句柄,用于按 HWND 重新绑定元素。
internal long NativeWindowHandle;
+ // 生成用于日志的简短描述(类型 / 名称)。
internal string Describe()
{
return (string.IsNullOrEmpty(ControlType) ? "未知类型" : ControlType)
@@ -175,6 +228,8 @@ namespace pacs_win_uia.Services
/// The picked element first, then its ancestors. The desktop is never probed or descended
/// into: enumerating the desktop would walk every window on the machine.
///
+ // 构建候选链 = 被拾取元素 + 逐级上级;绝不下钻/上探到桌面(否则会枚举整台机器的窗口)。
+ // 到达 MaxAncestorDepth 或顶层窗口即止;跨进程边界只记 Notices,不中断。
private static List BuildCandidateChain(
AutomationElement element,
ListReadOptions options,
@@ -249,6 +304,7 @@ namespace pacs_win_uia.Services
}
/// Probes the picked element and its ancestors for a real list pattern.
+ // 沿候选链向上逐一探测真正的列表模式(Table/Grid);返回首个成功的候选。元素中途失效时保留已读到的行。
private static ReadCandidate? ReadPatterns(
List candidates,
ListReadResult result,
@@ -287,6 +343,7 @@ namespace pacs_win_uia.Services
return null;
}
+ // 单个元素上的模式读取:TablePattern 优先于 GridPattern(要改这个先后顺序就改这里)。
private static bool TryReadPatterns(
AutomationElement element,
ListReadResult result,
@@ -298,6 +355,7 @@ namespace pacs_win_uia.Services
object patternObject;
// TablePattern first: it carries semantic row/column identity for real tables.
+ // 先试 TablePattern:真实表格里它带语义化的行/列标识,比 GridPattern 更可靠。
if (TryGetPattern(element, TablePattern.Pattern, out patternObject))
{
var table = (TablePattern)patternObject;
@@ -311,6 +369,7 @@ namespace pacs_win_uia.Services
}
ThrowIfStopped(stopwatch, options.Timeout, cancellationToken);
+ // 再试 GridPattern:无 TablePattern 的常见表格/网格走这里;行数为 0 视为不可用。
if (TryGetPattern(element, GridPattern.Pattern, out patternObject))
{
var grid = (GridPattern)patternObject;
@@ -331,6 +390,8 @@ namespace pacs_win_uia.Services
/// exposes the most columns wins; candidates are walked upwards until one yields a multi-column
/// level, and the single-column reading is only kept when no better level exists.
///
+ // 向上遍历降级:逐个候选试读;行元素的子级也“像”行层,因此取列数最多的一层(多列优先,
+ // 同列数时取更靠近被拾取元素者);只有单列结果才在没有更好层级时才保留。
private static ReadCandidate? ReadTraversalChain(
List candidates,
ListReadResult result,
@@ -402,6 +463,8 @@ namespace pacs_win_uia.Services
/// chain can never find it. Breadth-first so the shallowest list wins, bounded by a node
/// budget, a depth limit and the shared deadline.
///
+ // 在被拾取元素“内部”向下找列表(拾取整个窗口/页面容器时列表是其后代,向上链是够不到的)。
+ // 广度优先使最浅的列表先命中;受节点预算、深度上限与共享截止时间共同约束。
private static ReadCandidate? ReadDescendants(
List candidates,
ListReadResult result,
@@ -479,6 +542,8 @@ namespace pacs_win_uia.Services
/// capped, and a multi-column level beats a single-column one — a picked row's own cells also
/// "look like rows", which is exactly how a wrong answer would be produced.
///
+ // 向下遍历降级:找“暴露行但没有 Grid/Table 模式”的网页式列表;只探测能有子级的后代,
+ // 尝试次数受限;多列层级胜过单列层级(被拾取行自身的单元格也会“像”行,这正是误判的来源)。
private static ReadCandidate? ReadDescendantTraversal(
List candidates,
ListReadResult result,
@@ -554,6 +619,7 @@ namespace pacs_win_uia.Services
return DescribeCandidate(bestNode, start);
}
+ // 把向下找到的后代节点包装成候选:尝试读取其名称/类型/句柄,失败则沿用起点值。
private static ReadCandidate DescribeCandidate(DescendantNode node, ReadCandidate start)
{
var candidate = new ReadCandidate
@@ -581,12 +647,16 @@ namespace pacs_win_uia.Services
return candidate;
}
+ // 向下查找/遍历时队列里的一个节点。
private struct DescendantNode
{
+ // 节点元素。
internal AutomationElement Element;
+ // 相对起点的层数(0 = 起点本身)。
internal int Level;
}
+ // 返回结果里最宽的一行有多少列,用于判定多列结构。
private static int WidestRow(ListReadResult result)
{
int widest = 0;
@@ -598,6 +668,7 @@ namespace pacs_win_uia.Services
return widest;
}
+ // GridPattern 读取:记录真实行列总数,按 MaxRows/MaxColumns 截断,逐单元格取值。
private static void ReadGrid(
GridPattern grid,
ListReadResult result,
@@ -618,6 +689,7 @@ namespace pacs_win_uia.Services
CompleteStatus(result);
}
+ // TablePattern 读取:与 ReadGrid 类似,但行/列带语义标识,稳定性更好。
private static void ReadTable(
TablePattern table,
ListReadResult result,
@@ -638,6 +710,8 @@ namespace pacs_win_uia.Services
CompleteStatus(result);
}
+ // 逐行逐列读取单元格的公共骨架:先加行再调用 Provider(取消/超时也能保住当前行已读的单元格),
+ // 统计连续失败用于熔断;一个从未成功的 Provider 会被提前掐断并如实上报。
private static void ReadCells(
ListReadResult result,
int rows,
@@ -701,6 +775,7 @@ namespace pacs_win_uia.Services
}
}
+ // 全部单元格都读不到值时调用:标为 Partial 并加 Notices 说明“是不支持逐格访问,不代表列表没数据”。
private static void ReportAllCellsUnreadable(ListReadResult result, int failureCount)
{
result.IsComplete = false;
@@ -715,6 +790,8 @@ namespace pacs_win_uia.Services
/// (the WinForms DataGridView bridge is one). When that happens the pattern result carries
/// rows with no values at all, so the traversal is tried purely to rescue the values.
///
+ // 抢救取值:某些 Provider(如 WinForms DataGridView 桥)能给出 Grid/Table 的行列计数,
+ // 却每个单元格都失败;此时结果里只有空壳行,改用遍历纯粹把值取回来(先按 HWND 重新绑定)。
private static void TryRescueValuesWithTraversal(
ReadCandidate candidate,
ListReadResult result,
@@ -752,6 +829,7 @@ namespace pacs_win_uia.Services
}
/// Rebinds an element from its own HWND, falling back to the current reference.
+ // 由候选自身的 HWND 重新绑定元素(刚发生大量失败的 Provider 往往需要重绑才可用),失败则回退原引用。
private static AutomationElement Reacquire(ReadCandidate candidate)
{
if (candidate.NativeWindowHandle == 0)
@@ -776,6 +854,7 @@ namespace pacs_win_uia.Services
return candidate.Element;
}
+ // 统计结果里“既有元素又可取值”的单元格数量,用于判断是否需要抢救取值。
private static int CountAvailableValues(ListReadResult result)
{
int count = 0;
@@ -793,6 +872,7 @@ namespace pacs_win_uia.Services
return count;
}
+ // 把降级/抢救得到的 source 结果整体并入 target(来源、计数、列名、行与 Notices)。
private static void Adopt(ListReadResult target, ListReadResult source)
{
target.Source = source.Source;
@@ -827,6 +907,9 @@ namespace pacs_win_uia.Services
/// child of a row as a cell. Only rows the provider has already realized are visible, so the
/// result is never reported as complete.
///
+ // 遍历降级的核心:从容器向下找到“行层”,再把每行的每个子元素当作单元格。
+ // 虚拟化列表只能看到 Provider 已实现(可见/已滚到)的行,所以结果永不标为完整,
+ // 且行数只表示“当前已实现的行”而非逻辑总数(TotalRowsKnown=false),如实标注。
private static bool TryReadTraversal(
AutomationElement container,
ListReadResult result,
@@ -936,6 +1019,7 @@ namespace pacs_win_uia.Services
return result.Rows.Count > 0;
}
+ // 从起始元素逐层向下找“行层”:某一层的子元素通过 TryGetRowLevel 判定即为行集,否则选一个可下钻的子树继续。
private static List FindRowLevel(
AutomationElement start,
int maxDepth,
@@ -975,6 +1059,8 @@ namespace pacs_win_uia.Services
/// share a control type, and they either use a row control type, support selection, carry
/// usable names or stack vertically. Horizontally arranged siblings are cells, not rows.
///
+ // 判定一层子元素是否为“行集”:剔除表头/滚动条等 chrome(少量 chrome 不否决整层),
+ // 其余要么本身就是行控件类型,要么类型一致、支持选择、都有名字、或竖向堆叠——横向并排的兄弟是单元格而非行。
private static bool TryGetRowLevel(
List children,
TraversalState state,
@@ -1080,6 +1166,8 @@ namespace pacs_win_uia.Services
/// Control types that are single interactive elements, never a list container. Without this,
/// picking a button and traversing upward turns the button's own label into a one-row "list".
///
+ // 这些是“单个可交互控件”,绝不可能是列表容器。不跳过的话,拾取一个按钮再向上遍历,
+ // 按钮自己的标签就会被当成“一行列表”。要增删跳过的控件类就改这个 switch。
private static bool IsControlNotContainer(string controlTypeName)
{
if (string.IsNullOrEmpty(controlTypeName))
@@ -1116,6 +1204,7 @@ namespace pacs_win_uia.Services
}
/// True when every child is a header cell: that element is a header band, not a row.
+ // 每个子元素都是表头单元格时,该元素是表头带(WinForms 网格常见),不是数据行。
private static bool IsHeaderBand(AutomationElement element, TraversalState state)
{
List children = EnumerateChildren(element, state);
@@ -1135,6 +1224,7 @@ namespace pacs_win_uia.Services
return true;
}
+ // 子元素是否横向并排(第二个的左边界不早于第一个的右边界,含容差)——横向并排说明是单元格行。
private static bool HasHorizontallyArrangedChildren(AutomationElement parent, TraversalState state)
{
List children = EnumerateChildren(parent, state);
@@ -1154,6 +1244,7 @@ namespace pacs_win_uia.Services
return second.Left >= first.Right - tolerance;
}
+ // 从这一层里挑一个可下钻的子树:跳过被拒类型,最多看 8 个;有第一个子元素者即可继续向下。
private static AutomationElement FindDescentTarget(List children, TraversalState state)
{
int examined = 0;
@@ -1187,6 +1278,7 @@ namespace pacs_win_uia.Services
return null;
}
+ // 子元素是否竖向堆叠(第二个的上边界不早于第一个的下边界,含容差)。
private static bool IsVerticallyStacked(List children)
{
if (children.Count < 2)
@@ -1205,6 +1297,7 @@ namespace pacs_win_uia.Services
return second.Top >= first.Bottom - tolerance;
}
+ // 这些控件类型本身就是行(列表项/数据项/树项),命中即可直接认定为行层。
private static bool IsRowControlType(string controlTypeName)
{
return string.Equals(controlTypeName, "ControlType.ListItem", StringComparison.Ordinal)
@@ -1213,6 +1306,7 @@ namespace pacs_win_uia.Services
}
/// Control types that are never rows and never a descent target.
+ // 这些控件类型既不是行、也不能作为下钻目标(表头/滚动条/菜单/工具栏等 chrome)。
private static bool IsDeniedRowType(string controlTypeName)
{
if (string.IsNullOrEmpty(controlTypeName))
@@ -1242,6 +1336,8 @@ namespace pacs_win_uia.Services
}
}
+ // 读取一行的单元格:逐个非 chrome 子元素作为单元格(列号按顺序计),
+ // 若没有可寻址单元格则以行自身文本兜底(含制表符时按 \t 拆列,属降级推断)。
private static List ReadTraversalRow(
AutomationElement rowElement,
int rowIndex,
@@ -1316,6 +1412,9 @@ namespace pacs_win_uia.Services
/// Traversal-derived cells expose their text through Name first: the accessibility bridge for
/// legacy lists puts the cell text there, while Value/Text patterns are often absent.
///
+ // 遍历单元格的取值优先级:Edit/Document 先 ValuePattern(其 Name 是标签不是内容),
+ // 否则 Name 优先(旧式列表的无障碍桥把单元格文本放在 Name),再 ValuePattern、TextPattern,
+ // 最后尝试唯一的 Edit 子控件。取值失败则如实带 Error 返回。
private static ListCellResult ReadTraversalCell(
AutomationElement cell,
int rowIndex,
@@ -1414,6 +1513,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 列名来源优先级:先 TablePattern 的列头 API,再容器内 Header/HeaderItem 子元素名;都没有则占位并记 Notice。
private static List TryReadColumnNames(AutomationElement container, TraversalState state, IList notices)
{
List names = TryReadPatternColumnHeaders(container);
@@ -1432,6 +1532,7 @@ namespace pacs_win_uia.Services
return null;
}
+ // 仅 TablePattern 暴露列头 API(GridPattern 没有),能取到就返回列名。
private static List TryReadPatternColumnHeaders(AutomationElement container)
{
// Only TablePattern exposes column headers; GridPattern has no header API.
@@ -1448,6 +1549,7 @@ namespace pacs_win_uia.Services
return null;
}
+ // 读取一组表头元素的名称;任一元素读取失败时清空返回(宁可无列名也不要半截列名)。
private static List TryReadHeaderNames(Func getHeaders)
{
var names = new List();
@@ -1478,6 +1580,7 @@ namespace pacs_win_uia.Services
return names;
}
+ // 无列头 API 时的兜底:找容器里第一个 ControlType.Header 子元素,取其中每个 HeaderItem 的名称。
private static List TryReadHeaderChildNames(AutomationElement container, TraversalState state)
{
var names = new List();
@@ -1500,6 +1603,7 @@ namespace pacs_win_uia.Services
return names;
}
+ // 用已有列名补齐到 columnCount 列,缺失的以 Column0..N 占位。
private static void FillColumnNames(ListReadResult result, List columnNames, int columnCount)
{
result.ColumnNames.Clear();
@@ -1510,6 +1614,7 @@ namespace pacs_win_uia.Services
}
}
+ // 用 ControlViewWalker 枚举直接子元素;每访问一个即 Spend 一次预算;中途异常则返回已取到的部分。
private static List EnumerateChildren(AutomationElement parent, TraversalState state)
{
var children = new List();
@@ -1541,6 +1646,7 @@ namespace pacs_win_uia.Services
// ---------------------------------------------------------------- selection
+ // 读取选中项:选中状态挂在“容器”上而非用户点击的单元格;不支持 SelectionPattern 时静默跳过(不算失败)。
private static void TryReadSelection(
AutomationElement element,
ListReadResult result,
@@ -1624,6 +1730,7 @@ namespace pacs_win_uia.Services
// ---------------------------------------------------------------- cells
+ // 取 GridPattern 的单个单元格(GetItem 可能抛异常,失败则记为不可用单元格)。
private static ListCellResult ReadGridCell(GridPattern grid, int rowIndex, int columnIndex, ListReadOptions options)
{
try
@@ -1644,6 +1751,7 @@ namespace pacs_win_uia.Services
}
}
+ // 取 TablePattern 的单个单元格(同上,GetItem 失败记为不可用)。
private static ListCellResult ReadTableCell(TablePattern table, int rowIndex, int columnIndex, ListReadOptions options)
{
try
@@ -1664,6 +1772,7 @@ namespace pacs_win_uia.Services
}
}
+ // 通用单元格读取:元素存在即 IsAvailable=true,取值可用性由 ReadCellValue 决定。
private static ListCellResult ReadCell(AutomationElement cell, int rowIndex, int columnIndex, ListReadOptions options)
{
var result = new ListCellResult
@@ -1706,6 +1815,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 模式单元格的取值优先级:ValuePattern → TextPattern → Name(与遍历路径的偏好不同,见各自注释)。
private static string ReadCellValue(AutomationElement cell, ListReadOptions options, out ListValueSource source, out bool available)
{
string value;
@@ -1729,6 +1839,7 @@ namespace pacs_win_uia.Services
return name;
}
+ // 尝试 ValuePattern;不支持或异常返回 false(取消/超时异常照常抛出以中断本轮读取)。
private static bool TryReadValuePattern(AutomationElement element, out string value)
{
value = null;
@@ -1757,6 +1868,7 @@ namespace pacs_win_uia.Services
}
}
+ // 尝试 TextPattern;按 MaxTextLength 有界读取并裁掉行尾换行(无界 GetText(-1) 会整篇跨进程编组)。
private static bool TryReadTextPattern(AutomationElement element, ListReadOptions options, out string value)
{
value = null;
@@ -1791,6 +1903,7 @@ namespace pacs_win_uia.Services
}
}
+ // 编辑态单元格的文本常保存在其唯一的 Edit 子控件里;只有恰好一个 Edit 子级时才取值。
private static bool TryReadSingleEditChildValue(AutomationElement cell, TraversalState state, out string value)
{
value = null;
@@ -1808,6 +1921,7 @@ namespace pacs_win_uia.Services
return TryReadValuePattern(children[0], out value);
}
+ // 构造一个“元素不可用”的单元格结果,只带索引与错误信息。
private static ListCellResult FailedCell(int rowIndex, int columnIndex, Exception exception)
{
return new ListCellResult
@@ -1822,6 +1936,7 @@ namespace pacs_win_uia.Services
// ---------------------------------------------------------------- helpers
+ // 安全取模式的包装:元素失效等普通异常视为“不支持”,取消/超时异常照常抛出。
private static bool TryGetPattern(AutomationElement element, AutomationPattern pattern, out object patternObject)
{
patternObject = null;
@@ -1835,6 +1950,7 @@ namespace pacs_win_uia.Services
}
}
+ // 读取一次元素快照(名称、控件类型名、进程 ID、原生窗口句柄),供候选链判断使用。
private static UiaElementInfo Snapshot(AutomationElement element)
{
var snapshot = new UiaElementInfo { Element = element };
@@ -1846,6 +1962,7 @@ namespace pacs_win_uia.Services
return snapshot;
}
+ // 安全读取控件类型的编程名(如 ControlType.Text);读不到返回 null。
private static string TryReadControlTypeName(AutomationElement element)
{
try
@@ -1859,6 +1976,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全读取元素名称;读不到返回 null。
private static string TryReadName(AutomationElement element)
{
try
@@ -1871,6 +1989,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全读取元素边界矩形;读不到返回 Rect.Empty(用于横向/纵向排布判断)。
private static System.Windows.Rect TryReadBounds(AutomationElement element)
{
try
@@ -1883,6 +2002,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全执行一个计数取值委托(如 RowCount);异常时返回 0(= 不可用)。
private static int TryReadCount(Func getter)
{
try
@@ -1901,6 +2021,8 @@ namespace pacs_win_uia.Services
/// element is commonly reported as a Pane with class "#32769", so identity against
/// RootElement is the reliable test.
///
+ // 识别桌面根元素:绝不下钻/上探桌面(否则会枚举整台机器的所有窗口)。
+ // 托管 ControlType 没有 Desktop 成员,根元素常被报成 class "#32769" 的 Pane,故以 RootElement 身份为准。
private static bool IsDesktop(AutomationElement element)
{
if (element == null)
@@ -1926,6 +2048,7 @@ namespace pacs_win_uia.Services
}
+ // 校验读取选项的合法范围(各上限/预算/超时),非法即抛 ArgumentOutOfRangeException。
private static void ValidateOptions(ListReadOptions options)
{
if (options.MaxRows < 1)
@@ -1969,6 +2092,7 @@ namespace pacs_win_uia.Services
}
}
+ // 软截止检查点:已取消则抛 OperationCanceledException,超过 Timeout 则抛 TimeoutException。
private static void ThrowIfStopped(Stopwatch stopwatch, TimeSpan timeout, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -1978,6 +2102,7 @@ namespace pacs_win_uia.Services
}
}
+ // 收尾定级:未处于终态(Unsupported/Failed/Canceled/TimedOut)时,按是否完整定 Success 或 Partial。
private static void CompleteStatus(ListReadResult result)
{
if (result.Status != ListReadStatus.Unsupported && result.Status != ListReadStatus.Failed &&
@@ -1987,6 +2112,7 @@ namespace pacs_win_uia.Services
}
}
+ // 因 MaxRows/MaxColumns 截断时:标为 Partial 并记录一条限制错误。
private static void AddLimitError(ListReadResult result, bool rowsLimited, bool columnsLimited)
{
if (rowsLimited || columnsLimited)
@@ -1997,6 +2123,7 @@ namespace pacs_win_uia.Services
}
}
+ // 追加一条错误,受 MaxErrors 上限约束(0 表示不限制)。
private static void AddError(ListReadResult result, string error, int maxErrors)
{
if (maxErrors == 0 || result.Errors.Count < maxErrors)
@@ -2005,6 +2132,7 @@ namespace pacs_win_uia.Services
}
}
+ // 新建一个中间结果(指定来源,初始 Status=Partial、IsComplete=true,随后按实际调整)。
private static ListReadResult NewResult(ListReadSource source)
{
return new ListReadResult
@@ -2015,6 +2143,7 @@ namespace pacs_win_uia.Services
};
}
+ // 终态:目标不支持/找不到可读取的列表(找不到 ≠ 空列表),置 Unsupported 并带错误信息。
private static ListReadResult Unsupported(ListReadResult result, string message)
{
result.Status = ListReadStatus.Unsupported;
@@ -2024,6 +2153,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 终态:读取过程抛出异常导致失败,置 Failed 并记录格式化后的异常。
private static ListReadResult Failed(ListReadResult result, Exception exception)
{
result.Status = ListReadStatus.Failed;
@@ -2033,6 +2163,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 终态:因取消或超时停止,置对应状态(Canceled/TimedOut)并带说明。
private static ListReadResult MarkStopped(ListReadResult result, ListReadStatus status, string message)
{
result.Status = status;
@@ -2046,6 +2177,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 把异常格式化成简短可读文本:元素失效 / COM 错误(含 HRESULT)/ 普通 类型名+消息。
private static string FormatException(Exception exception)
{
if (exception is ElementNotAvailableException)
@@ -2062,13 +2194,19 @@ namespace pacs_win_uia.Services
}
/// Bounds the traversal by both a deadline and a node budget.
+ // 遍历的“预算 + 截止时间”状态:同时受节点上限与共享超时约束,供所有遍历路径复用。
private sealed class TraversalState
{
+ // 共享的计时器(整个读取共用)。
private readonly Stopwatch _stopwatch;
+ // 软截止时长(InfiniteTimeSpan 表示不限时)。
private readonly TimeSpan _timeout;
+ // 取消令牌。
private readonly CancellationToken _cancellationToken;
+ // 剩余可用节点数。
private int _remainingNodes;
+ // 以节点上限、计时器、超时与取消令牌初始化。
internal TraversalState(int maxNodes, Stopwatch stopwatch, TimeSpan timeout, CancellationToken cancellationToken)
{
_remainingNodes = maxNodes;
@@ -2077,6 +2215,7 @@ namespace pacs_win_uia.Services
_cancellationToken = cancellationToken;
}
+ // 消耗一个节点预算:取消/超时/预算耗尽都会抛出对应异常。
internal void Spend()
{
_cancellationToken.ThrowIfCancellationRequested();
diff --git a/src/pacs_win_uia/Services/ListResultExporter.cs b/src/pacs_win_uia/Services/ListResultExporter.cs
index 043c4ce..1ee9679 100644
--- a/src/pacs_win_uia/Services/ListResultExporter.cs
+++ b/src/pacs_win_uia/Services/ListResultExporter.cs
@@ -1,3 +1,17 @@
+// ===========================================================================
+// ListResultExporter —— 列表结果导出(JSON / CSV)
+//
+// 职责:把 ListReadResult 序列化成显式 JSON 或标准兼容 CSV 快照;导出由用户主动触发。
+// 被谁调用:MainForm 的导出操作(_listResultExporter.ExportCsv / ExportJson)。
+// 读取策略顺序:本类不读取、只序列化;数据来源见 ListReaderService 的文件头。
+// “找不到 ≠ 空列表”:导出如实反映结果状态(Unsupported/Failed 也会照常导出,不伪装成空表)。
+// 预算与超时:无;CSV 列数受 MaxCsvColumns 上限约束。
+// 数据安全与防护:
+// - JSON 通过 [DataContract] 的显式字段序列化,不做隐式反射;值可能含敏感医疗信息,调用方须提示用户。
+// - CSV 对以 = + - @ 开头的值加前导单引号,防止表格软件把医疗文本当公式执行(公式前缀防护)。
+// - 注意:本类不做脱敏/匿名化,仅做公式前缀防护与 CSV 转义;要改防护规则就改 EscapeCsv。
+// ===========================================================================
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -12,10 +26,13 @@ namespace pacs_win_uia.Services
/// Exports list results as explicit JSON or standards-compatible CSV snapshots.
/// Export is user initiated; callers should warn that values may contain sensitive data.
///
+ // 导出器:只负责把结果写成 JSON/CSV,不做读取;值可能含敏感数据,由调用方提示用户。
public sealed class ListResultExporter
{
+ // CSV 导出的最大列数上限,防止异常结果产生超宽表。
private const int MaxCsvColumns = 10000;
+ // 序列化为 JSON 字符串:用 DataContractJsonSerializer 按显式契约字段输出(UTF-8,无 BOM)。
public string SerializeJson(ListReadResult result)
{
if (result == null)
@@ -31,11 +48,13 @@ namespace pacs_win_uia.Services
}
}
+ // 导出为 JSON 文件(UTF-8 无 BOM,显式契约序列化)。
public void ExportJson(ListReadResult result, string filePath)
{
WriteText(filePath, SerializeJson(result), new UTF8Encoding(false));
}
+ // 序列化为 CSV 字符串:首行是含元数据列的表头,其后每行一条记录(无数据行时输出一行元数据)。
public string SerializeCsv(ListReadResult result)
{
if (result == null)
@@ -62,11 +81,13 @@ namespace pacs_win_uia.Services
return builder.ToString();
}
+ // 导出为 CSV 文件(UTF-8 带 BOM,便于 Excel 正确识别中文)。
public void ExportCsv(ListReadResult result, string filePath)
{
WriteText(filePath, SerializeCsv(result), new UTF8Encoding(true));
}
+ // 写 CSV 表头:先固定若干 __ 前缀的元数据列,再补各数据列名(缺名者以 ColumnN 占位)。
private static void AppendCsvHeader(StringBuilder builder, ListReadResult result, int columns)
{
var headers = new List
@@ -106,6 +127,7 @@ namespace pacs_win_uia.Services
builder.AppendLine();
}
+ // 写一行记录:先元数据列(读取时间/状态/来源/完整性/计数/错误/选中项/行信息),再按列号填单元格值。
private static void AppendCsvRow(StringBuilder builder, ListReadResult result, ListRowResult row, int columns)
{
var fields = new List
@@ -126,6 +148,7 @@ namespace pacs_win_uia.Services
row == null ? BuildErrors(result) : BuildCellMetadata(row)
};
+ // 逐列填值:单元格缺失留空;元素在但取不到值则以“ [不可用] + 原因”如实标注,不冒充空值。
for (int columnIndex = 0; columnIndex < columns; columnIndex++)
{
ListCellResult cell = row == null ? null : FindCell(row, columnIndex);
@@ -147,6 +170,7 @@ namespace pacs_win_uia.Services
builder.AppendLine();
}
+ // 求列数:列名数与各行单元格最大 ColumnIndex+1 的较大者。
private static int GetMaxColumns(ListReadResult result)
{
int max = result.ColumnNames.Count;
@@ -164,6 +188,7 @@ namespace pacs_win_uia.Services
return max;
}
+ // 在行内按列号查找单元格(行内单元格未按列号排序,故线性查找)。
private static ListCellResult FindCell(ListRowResult row, int columnIndex)
{
foreach (ListCellResult cell in row.Cells)
@@ -177,6 +202,7 @@ namespace pacs_win_uia.Services
return null;
}
+ // 把顶层 Error 与 Errors 明细合并成一个用 " | " 连接的字符串(供 CSV 元数据列)。
private static string BuildErrors(ListReadResult result)
{
var errors = new List();
@@ -188,6 +214,7 @@ namespace pacs_win_uia.Services
return string.Join(" | ", errors.ToArray());
}
+ // 把选中项拼成 "序号|行标识|名称" 用 ";" 连接的一列文本(供 CSV 元数据列)。
private static string BuildSelectedItems(ListReadResult result)
{
var values = new List();
@@ -204,6 +231,7 @@ namespace pacs_win_uia.Services
return string.Join(";", values.ToArray());
}
+ // 把一行内每个单元格的元数据(列号|列标识|值来源|可取到值|元素可用|错误)用 ";" 连成一列文本。
private static string BuildCellMetadata(ListRowResult row)
{
var values = new List();
@@ -223,6 +251,7 @@ namespace pacs_win_uia.Services
return string.Join(";", values.ToArray());
}
+ // CSV 字段转义:公式前缀防护 + 引号转义 + 必要时整体加引号(要改防护规则就改这里)。
private static string EscapeCsv(string value)
{
if (value == null)
@@ -236,11 +265,13 @@ namespace pacs_win_uia.Services
value = "'" + value;
}
+ // 含逗号/双引号/换行时整体加引号,内部双引号成对转义。
bool quoted = value.IndexOfAny(new[] { ',', '"', '\r', '\n' }) >= 0;
string escaped = value.Replace("\"", "\"\"");
return quoted ? "\"" + escaped + "\"" : escaped;
}
+ // 写文本文件:校验路径、自动创建目录,再按指定编码写盘。
private static void WriteText(string filePath, string content, Encoding encoding)
{
if (string.IsNullOrWhiteSpace(filePath))
diff --git a/src/pacs_win_uia/Services/MsaaService.cs b/src/pacs_win_uia/Services/MsaaService.cs
index e155b00..b728d1c 100644
--- a/src/pacs_win_uia/Services/MsaaService.cs
+++ b/src/pacs_win_uia/Services/MsaaService.cs
@@ -1,3 +1,17 @@
+// =============================================================================
+// MsaaService —— MSAA(IAccessible)的只读访问层。
+// 职责:把 AccessibleObjectFromWindow / AccessibleObjectFromPoint / accHitTest / accChild 等 COM 调用
+// 包成安全快照:TryGetRoot(OBJID_CLIENT→OBJID_WINDOW 回退)、ReadSelf(单节点)、
+// ReadChildren(批量子节点),以及两个命中测试。所有返回值都是可序列化的原始值,不当场持有活动对象。
+// 被谁调用:MsaaTreeReader(树遍历)与命中测试路径;本身不直接被 UI 调用。
+// 线程模型:每一次调用都是跨进程 COM 调用,可能阻塞在无响应的目标上,因此调用方必须放在 UI/MainForm.cs
+// 的 LongRunning 专用线程,并用 ReadBudget 的截止时间在调用间隙收口(在途 COM 调用无法中断)。
+// 要改什么就改哪里:
+// - 改根对象回退策略 → TryGetRoot。
+// - 改批量子节点策略/批量大小 → ReadChildren / BatchSize。
+// - COM 释放规则:child 与父可能是同一个 RCW,见各处 ReferenceEquals 判断——绝不可二次 ReleaseComObject。
+// =============================================================================
+
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -9,14 +23,20 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // MSAA 子节点:要么是简单 childId(叶子),要么是 COM 子对象(可递归)。
/// A child returned by an MSAA walk: either a simple child id or a COM child object.
internal sealed class MsaaChild
{
+ // COM 子对象;简单 childId 时为 null。
internal IAccessible Accessible;
+ // 简单子 ID;对象子节点使用 CHILDID_SELF。
internal object ChildId;
+ // 稳定路径键(0xHWND/iN/oN),供 XPath/定位使用。
internal string PathKey;
+ // true=COM 子对象可下钻;false=简单 childId 叶子。
internal bool IsObject;
+ // 释放 COM 对象(尽力而为,失败不影响读取);释放后置空,杜绝重复释放。
internal void Release()
{
if (Accessible != null)
@@ -35,14 +55,17 @@ namespace pacs_win_uia.Services
}
}
+ // 只读 MSAA 访问;每个方法都是可能阻塞的跨进程 COM 调用。
///
/// Read-only MSAA access. Every call is a cross-process COM call that can block on a hung
/// target, so callers must run this on a dedicated thread with a deadline (see ControlTreeService).
///
public sealed class MsaaService
{
+ // AccessibleChildren 一次批量取子的数量,减少 COM 往返次数。
private const int BatchSize = 128;
+ // 取窗口根对象:先 OBJID_CLIENT(真内容),失败回退 OBJID_WINDOW(任何 HWND 都有)。
///
/// Root object for a window: OBJID_CLIENT first (the real content), falling back to
/// OBJID_WINDOW, which every HWND answers.
@@ -74,6 +97,7 @@ namespace pacs_win_uia.Services
return false;
}
+ // 按 objectId 取 IAccessible;失败时把 HRESULT 转成可读文本返回。
private static bool TryGetObject(IntPtr hwnd, uint objectId, out object accessible, out string error)
{
accessible = null;
@@ -105,6 +129,7 @@ namespace pacs_win_uia.Services
}
}
+ // 全屏命中测试;叶子可能是返回对象本身,也可能是 childId。
/// Point hit test. The leaf may be the child id rather than the returned object.
public bool TryHitTest(Point point, out MsaaNodeInfo info, out IntPtr windowHandle, out string error)
{
@@ -189,6 +214,7 @@ namespace pacs_win_uia.Services
}
}
+ // 在指定窗口自身的对象上做 accHitTest(屏幕坐标),比全局命中更深。
///
/// Hit test performed *on a specific window's own accessible object*. This reaches much
/// deeper than the global AccessibleObjectFromPoint (which often answers with the top-level
@@ -284,6 +310,7 @@ namespace pacs_win_uia.Services
}
}
+ // 把对象的 Name/Value/Role/State/Location 等读成一个可序列化快照。
/// Snapshot of one node (the object itself, or a simple child id read through it).
public MsaaNodeInfo ReadSelf(IAccessible accessible, object childId, string pathKey)
{
@@ -316,6 +343,7 @@ namespace pacs_win_uia.Services
return info;
}
+ // 批量读取子节点;AccessibleChildren 失败时回退逐个 accChild。
///
/// Children of a node, in batches. AccessibleChildren returns a mix of simple child ids
/// (int, leaves, no HWND) and child objects (IAccessible, recurse) — both must be handled.
@@ -443,6 +471,7 @@ namespace pacs_win_uia.Services
return children;
}
+ // 逐个回退:用 accChild 读取第 index+1 个子节点(AccessibleChildren 不可用时)。
private static MsaaChild ReadSingleChild(IAccessible accessible, int index, string pathKey)
{
try
@@ -474,6 +503,7 @@ namespace pacs_win_uia.Services
}
}
+ // 用 WindowFromAccessibleObject 取子对象所属 HWND(可选信息,失败不致命)。
private static void TryReadWindow(IAccessible accessible, MsaaNodeInfo info, out IntPtr windowHandle)
{
windowHandle = IntPtr.Zero;
@@ -494,6 +524,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全读取字符串属性,异常转进错误列表。
private static string TryRead(Func getter, ICollection errors, string name)
{
try
@@ -507,6 +538,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全读取对象属性(role/state),异常转进错误列表。
private static object TryReadObject(Func
public sealed class OcrReadContext
{
+ // 私有构造:只允许 Create 在 OCR 开启时创建(构造即建立客户端与截图服务)。
private OcrReadContext(OcrSettings settings)
{
Settings = settings;
@@ -39,12 +62,16 @@ namespace pacs_win_uia.Services
Screenshots = new ScreenshotService();
}
+ // OCR 相关设置。
public OcrSettings Settings { get; private set; }
+ // 已按设置建好的 OCR 客户端。
public OcrClient Client { get; private set; }
+ // 用于给 OCR 提供截图的服务。
public ScreenshotService Screenshots { get; private set; }
+ // 工厂:OCR 关闭(默认)时返回 null。
/// Null when OCR is off, which is the default.
public static OcrReadContext Create(OcrSettings settings)
{
@@ -67,19 +94,28 @@ namespace pacs_win_uia.Services
/// i2t is asynchronous: it may answer "queued"/"processing" first, so it is polled until the task
/// finishes or the timeout expires. The image only ever goes to the configured address, and the
/// recognized text is never written to the log (it can contain patient data).
+ /// 本地 OCR 服务客户端;i2t 为异步轮询;图片只发往配置地址,识别文本不写日志。
///
public sealed class OcrClient
{
+ // 上传接口路径。
private const string UploadPath = "/api/v1/upload";
+ // 图片转文字接口路径。
private const string I2TPath = "/api/v1/i2t";
+ // 健康检查接口路径。
private const string HealthPath = "/healthz";
+ // 轮询识别结果的间隔(500ms)。
private static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(500);
+ // 服务基地址(已去掉结尾斜杠)。
private readonly string _baseUrl;
+ // 传给服务端的最低置信度阈值。
private readonly double _minConfidence;
+ // 等待一次识别完成的整体超时。
private readonly TimeSpan _timeout;
+ // 由设置构造:校验非空、套用默认值,缓存基地址/置信度/超时。
public OcrClient(OcrSettings settings)
{
if (settings == null)
@@ -93,11 +129,13 @@ namespace pacs_win_uia.Services
_timeout = TimeSpan.FromSeconds(Math.Max(1, settings.TimeoutSeconds));
}
+ // 当前使用的服务基地址(只读)。
public string BaseUrl
{
get { return _baseUrl; }
}
+ // 存活探测:GET /healthz,非 200 或异常都返回 false 并给出原因。
public bool CheckHealth(out string error)
{
error = null;
@@ -125,6 +163,7 @@ namespace pacs_win_uia.Services
}
/// Recognizes an image; the caller keeps ownership of the bitmap.
+ /// 识别一张图:先上传拿到 file_id,再轮询 i2t 直到 completed/failed/超时;位图归调用方所有。
public OcrResult Recognize(Bitmap image, string screenshotPath)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
@@ -186,6 +225,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 以 multipart 形式把 PNG 上传到 /api/v1/upload,取出返回里的 file_id。
private bool TryUpload(Bitmap image, out string fileId, out string error)
{
fileId = null;
@@ -243,6 +283,7 @@ namespace pacs_win_uia.Services
}
}
+ // 向 /api/v1/i2t 提交/查询一次:带 file_id 与最低置信度,解析出 status/progress/text/队列位置。
private bool TryI2T(
string fileId,
out string status,
@@ -300,12 +341,14 @@ namespace pacs_win_uia.Services
}
}
+ // 把字符串按 UTF-8 写入流(用于拼 multipart 报文)。
private static void WriteAscii(Stream stream, string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
+ // 用 DataContractJsonSerializer 把响应流反序列化成统一信封 Envelope。
private static Envelope ReadEnvelope(Stream stream)
{
if (stream == null)
@@ -317,6 +360,7 @@ namespace pacs_win_uia.Services
return (Envelope)serializer.ReadObject(stream);
}
+ // 把异常翻译成中文失败描述:网络异常带上 WebException 状态/HTTP 码/截短的响应体。
private static string Describe(Exception exception, string prefix)
{
if (exception is WebException)
@@ -353,48 +397,62 @@ namespace pacs_win_uia.Services
// ---------------------------------------------------------------- wire contracts
+ // 服务端统一响应信封:{ code, message, data }。
[DataContract]
private sealed class Envelope
{
+ // 业务状态码。
[DataMember(Name = "code")]
public int Code { get; set; }
+ // 提示信息(出错时用)。
[DataMember(Name = "message")]
public string Message { get; set; }
+ // 实际数据体。
[DataMember(Name = "data")]
public Payload Data { get; set; }
}
/// Union of the upload and i2t payloads: both endpoints use the same envelope.
+ /// upload 与 i2t 两种响应数据的并集:两个接口共用同一信封结构。
[DataContract]
private sealed class Payload
{
+ // upload 返回的图片标识,用于随后查询识别结果。
[DataMember(Name = "file_id")]
public string FileId { get; set; }
+ // 识别任务状态:queued/processing/completed/failed 等。
[DataMember(Name = "status")]
public string Status { get; set; }
+ // 进度百分比。
[DataMember(Name = "progress")]
public int Progress { get; set; }
+ // 队列中的位置(可为空)。
[DataMember(Name = "queue_position")]
public int? QueuePosition { get; set; }
+ // 服务端处理耗时(毫秒)。
[DataMember(Name = "elapsed_ms")]
public double ElapsedMs { get; set; }
+ // 识别结果文档(完成时才有)。
[DataMember(Name = "result")]
public Document Result { get; set; }
+ // 服务端错误信息。
[DataMember(Name = "error")]
public string Error { get; set; }
}
+ // 识别结果文档:目前只有识出的文本。
[DataContract]
private sealed class Document
{
+ // 识别出的文本内容。
[DataMember(Name = "text")]
public string Text { get; set; }
}
diff --git a/src/pacs_win_uia/Services/ProcessJob.cs b/src/pacs_win_uia/Services/ProcessJob.cs
index 75ddb55..4ce40de 100644
--- a/src/pacs_win_uia/Services/ProcessJob.cs
+++ b/src/pacs_win_uia/Services/ProcessJob.cs
@@ -1,3 +1,29 @@
+// =============================================================================
+// ProcessJob.cs —— Windows 作业对象(Job Object)封装,保证退出时结束整棵进程树
+//
+// 职责:
+// 创建带 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 的作业对象。把本工具启动的每个命令进程
+// 加入该作业;命令自己再拉起的子进程会「继承」进同一作业。
+//
+// 为什么需要它(关掉句柄 = 杀整棵树):
+// 关闭作业句柄时(正常退出、Dispose、甚至本进程被杀导致 OS 关闭句柄),操作系统会
+// 结束作业内所有进程。只杀我们启动的 cmd.exe 会把它拉起的应用留下;正是这个作业让
+// 「退出时把命令和它拉起的应用一起结束」成立。
+//
+// 被谁调用:
+// CommandRunner 持有并调用 TryAssign / Dispose(见 CommandRunner 的 _job 字段)。
+//
+// 边界条件:
+// 加入作业可能失败(进程已退出、或旧的父作业禁止嵌套);失败只记日志,调用方仍有显式
+// KillProcessTree 作为兜底。IsAvailable=false 时调用方必须自行结束进程。
+//
+// 注意(P/Invoke):
+// JOBOBJECT_* 结构字段布局必须与 Win32 完全一致(尤其是 UIntPtr/对齐),否则
+// SetInformationJobObject 会失败;这是平台相关的调用。
+//
+// 要改什么就改哪里:
+// 作业限制标志 -> JobObjectLimitKillOnJobClose 与构造函数里的 LimitFlags。
+// =============================================================================
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
@@ -5,6 +31,7 @@ using pacs_win_uia.Diagnostics;
namespace pacs_win_uia.Services
{
+ // 作业对象封装:把命令进程及其子进程收进一个可一次性结束的作业。
///
/// A Windows job object created with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.
///
@@ -20,12 +47,17 @@ namespace pacs_win_uia.Services
///
public sealed class ProcessJob : IDisposable
{
+ // SetInformationJobObject 的信息类别:扩展限制信息(=9)。
private const int JobObjectExtendedLimitInformation = 9;
+ // 限制标志:作业句柄关闭时结束作业内所有进程(0x2000)。
private const uint JobObjectLimitKillOnJobClose = 0x2000;
+ // 作业对象句柄;IntPtr.Zero 表示创建失败(IsAvailable=false)。
private IntPtr _handle;
+ // 是否已释放,避免重复关闭句柄。
private bool _disposed;
+ // 创建作业并设置「句柄关闭即结束」;失败不抛异常,只记日志并把 IsAvailable 置为 false。
public ProcessJob()
{
try
@@ -67,12 +99,14 @@ namespace pacs_win_uia.Services
}
}
+ // 作业是否可用;false 时调用方必须自行显式结束进程。
/// False when the job could not be created; callers must then kill explicitly.
public bool IsAvailable
{
get { return _handle != IntPtr.Zero; }
}
+ // 把刚启动的进程加入作业;其后续子进程会因继承而自动进入同一作业。
/// Puts a freshly started process (and, by inheritance, its children) into the job.
public bool TryAssign(Process process)
{
@@ -100,6 +134,7 @@ namespace pacs_win_uia.Services
}
}
+ // 关闭作业句柄——这一步就是「结束作业内所有进程」;随后置零避免重复关闭。
public void Dispose()
{
if (_disposed)
@@ -119,51 +154,79 @@ namespace pacs_win_uia.Services
_handle = IntPtr.Zero;
}
+ // 创建作业对象;name 传 null 表示匿名作业。
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr CreateJobObject(IntPtr securityAttributes, string name);
+ // 设置作业信息(此处用扩展限制信息,携带 KillOnJobClose 标志)。
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetInformationJobObject(IntPtr job, int informationClass, IntPtr information, uint length);
+ // 把进程加入作业;作业内的子进程会继承作业资格。
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
+ // 关闭内核句柄(对作业而言即触发结束全部成员进程)。
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);
+ // 作业基本限制信息(Win32 JOBOBJECT_BASIC_LIMIT_INFORMATION),字段布局须与系统一致。
[StructLayout(LayoutKind.Sequential)]
private struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
+ // 每进程用户态时间上限(100ns)。
public long PerProcessUserTimeLimit;
+ // 每作业用户态时间上限(100ns)。
public long PerJobUserTimeLimit;
+ // 限制标志位;我们只置 KillOnJobClose。
public uint LimitFlags;
+ // 最小工作集(字节)。
public UIntPtr MinimumWorkingSetSize;
+ // 最大工作集(字节)。
public UIntPtr MaximumWorkingSetSize;
+ // 作业内活动进程数上限。
public uint ActiveProcessLimit;
+ // 处理器亲和性掩码。
public UIntPtr Affinity;
+ // 优先级类。
public uint PriorityClass;
+ // 调度类。
public uint SchedulingClass;
}
+ // 作业 I/O 计数(Win32 IO_COUNTERS),本工具不使用其值,仅为结构对齐而保留。
[StructLayout(LayoutKind.Sequential)]
private struct IO_COUNTERS
{
+ // 读操作次数。
public ulong ReadOperationCount;
+ // 写操作次数。
public ulong WriteOperationCount;
+ // 其它操作次数。
public ulong OtherOperationCount;
+ // 读取字节数。
public ulong ReadTransferCount;
+ // 写入字节数。
public ulong WriteTransferCount;
+ // 其它传输字节数。
public ulong OtherTransferCount;
}
+ // 作业扩展限制信息(Win32 JOBOBJECT_EXTENDED_LIMIT_INFORMATION),SetInformationJobObject 用它。
[StructLayout(LayoutKind.Sequential)]
private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
+ // 基本限制信息块。
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
+ // I/O 计数块(仅占位)。
public IO_COUNTERS IoInfo;
+ // 单进程内存上限(字节)。
public UIntPtr ProcessMemoryLimit;
+ // 整作业内存上限(字节)。
public UIntPtr JobMemoryLimit;
+ // 峰值单进程内存。
public UIntPtr PeakProcessMemoryUsed;
+ // 峰值整作业内存。
public UIntPtr PeakJobMemoryUsed;
}
}
diff --git a/src/pacs_win_uia/Services/ReadBudget.cs b/src/pacs_win_uia/Services/ReadBudget.cs
index db8eee1..355d02a 100644
--- a/src/pacs_win_uia/Services/ReadBudget.cs
+++ b/src/pacs_win_uia/Services/ReadBudget.cs
@@ -1,3 +1,19 @@
+// =============================================================================
+// ReadBudget —— UIA / MSAA / Win32 三种控件树读取器共用的“读取预算”对象。
+// 职责:统一四道闸门——最大深度 MaxDepth、最大节点数 MaxNodes、超时截止时间 Deadline、取消令牌
+// CancellationToken。任何来源都必须共用同一个 ReadBudget,否则单个读取器可能无限递归或
+// 无限次发起跨进程调用。
+// 线程模型:三种读取器都运行在 UI/MainForm.cs 的 LongRunning 专用线程上(TaskCreationOptions.
+// LongRunning),绝不占用 UI 线程。跨进程同步调用(UIA/MSAA 的 COM 调用、Win32 的
+// SendMessageTimeout)一旦发出就无法中断;因此 Deadline/Cancel 只能在“两次调用之间”生效——
+// 它限制的是“还能再发起多少工作”,而不是掐断一次已在途的调用。这正是“读取可能超时但不会
+// 卡死界面”的原因。
+// 要改什么就改哪里:
+// - 改默认上限/默认超时 → Models/ControlTreeNode.cs 的 ControlTreeOptions 构造函数。
+// - 改闸门判定逻辑/抛出的异常类型 → 本文件。
+// - 新增读取来源时,务必在每个循环入口调用 ThrowIfStopped(),并在纳入一个节点时 CountNode()。
+// =============================================================================
+
using System;
using System.Threading;
@@ -10,8 +26,10 @@ namespace pacs_win_uia.Services
///
public sealed class ReadBudget
{
+ // 已计入的节点数;初始为 1,因为根节点本身也算一个节点。
private int _nodeCount;
+ // 校验参数并计算截止时间:InfiniteTimeSpan 表示永不超时;非正超时表示立即过期。
public ReadBudget(int maxDepth, int maxNodes, TimeSpan timeout, CancellationToken cancellationToken)
{
if (maxDepth < 0)
@@ -35,34 +53,43 @@ namespace pacs_win_uia.Services
_nodeCount = 1;
}
+ // 最大递归深度;达到后不再下钻,子节点标记 MaxDepthReached。
public int MaxDepth { get; private set; }
+ // 单次读取允许的最大节点总数。
public int MaxNodes { get; private set; }
+ // 当前已计数的节点数(含根节点)。
public int NodeCount
{
get { return _nodeCount; }
}
+ // 截止时间(UTC);IsExpired 与 ThrowIfStopped 都以此为准。
public DateTime Deadline { get; private set; }
+ // 调用方传入的取消令牌,通常与窗体关闭令牌联动。
public CancellationToken CancellationToken { get; private set; }
+ // 是否已达到节点上限,供遍历循环提前收尾。
public bool IsNodeLimitReached
{
get { return _nodeCount >= MaxNodes; }
}
+ // 是否已过截止时间。
public bool IsExpired
{
get { return DateTime.UtcNow > Deadline; }
}
+ // 每纳入一个节点调用一次,递增计数。
public void CountNode()
{
_nodeCount++;
}
+ // 四道闸门的统一检查点:先响应取消,再检查超时;在途调用无法中断,故只能在调用间隙抛出。
public void ThrowIfStopped()
{
CancellationToken.ThrowIfCancellationRequested();
diff --git a/src/pacs_win_uia/Services/ScreenshotService.cs b/src/pacs_win_uia/Services/ScreenshotService.cs
index bf1e835..e3c6241 100644
--- a/src/pacs_win_uia/Services/ScreenshotService.cs
+++ b/src/pacs_win_uia/Services/ScreenshotService.cs
@@ -8,33 +8,59 @@ using pacs_win_uia.Diagnostics;
using pacs_win_uia.Interop;
using pacs_win_uia.Models;
+// ============================================================================
+// ScreenshotService.cs —— 截图服务(只读抓取目标窗口的像素)
+// 职责:捕获窗口/客户区/屏幕矩形,按优先级依次尝试多种截图方式,并对结果做有效性校验。
+// 被谁调用:HeadlessConfigReader(取值失败时的 OCR 降级路径)、ControlValueReader 的 OcrText 分支、
+// 以及 UI 需要保存截图证据的地方。
+// 截图方式优先级:PrintWindow(PW_RENDERFULLCONTENT) → PrintWindow(0) → BitBlt → 屏幕拷贝(ScreenCopy)。
+// PW_RENDERFULLCONTENT 能截到很多 GPU 合成窗口(Win8.1+);越靠后越是兜底。
+// 有效性校验:TryValidate 采样整图,全黑/全白/颜色过于单一都判失败——API 返回成功并不等于图可用。
+// 最小化窗口:默认不截;只有设置里显式授权“临时恢复最小化窗口”才会临时恢复,
+// 那会闪屏并可能改变前台窗口,事后再恢复最小化并尝试还原原前台窗口。
+// 敏感数据提示:截图可能含患者数据,落盘位置与文件请谨慎保管;OCR 用图只在本地服务之间流转。
+// 限制与已知问题:屏幕拷贝(ScreenCopy)在窗口被遮挡时会截到遮挡物;BitBlt/PrintWindow 对
+// 部分自绘或硬件加速界面可能返回黑图,只能靠有效性校验兜底。
+// 要改什么就改哪里:
+// - 截图方式顺序 / 新增方式:CaptureWindow 里的调用顺序,以及 TryCaptureWith/TryBitBlt/TryScreenCopy。
+// - 有效性判定阈值(全黑全白、颜色单一):TryValidate。
+// - 落盘命名与目录:Save / Sanitize / ExecutableDirectory。
+// ============================================================================
namespace pacs_win_uia.Services
{
public enum ScreenshotTarget
{
+ // 截图目标:整个窗口(含边框标题栏)。
/// Whole window including the frame.
Window,
+ // 截图目标:仅客户区(不含边框,用 PW_CLIENTONLY 让窗口只画客户区)。
/// Client area only.
Client,
+ // 截图目标:显式给定的屏幕矩形(不走窗口 API,直接用屏幕拷贝)。
/// An explicit screen rectangle.
Rectangle
}
public enum ScreenshotMethod
{
+ // 未用任何方式截到图(默认值/失败)。
None,
+ // 首选:PrintWindow 带 PW_RENDERFULLCONTENT,能截到很多 GPU 合成窗口(Win8.1+)。
/// PrintWindow with PW_RENDERFULLCONTENT (works for many GPU-composited windows on Win 8.1+).
PrintWindowFull,
+ // 次选:普通 PrintWindow(不带 RENDERFULLCONTENT),对部分老式窗口更有效。
/// Plain PrintWindow.
PrintWindow,
+ // 再次:从窗口 DC 做 BitBlt。
/// BitBlt from the window DC.
BitBlt,
+ // 兜底:屏幕拷贝,仅当窗口确实可见且未被遮挡时才有效。
/// Screen copy: only valid while the window is actually visible and unobstructed.
ScreenCopy
}
@@ -49,16 +75,20 @@ namespace pacs_win_uia.Services
AllowScreenCopyFallback = true;
}
+ // 截图目标(窗口/客户区/矩形)。
public ScreenshotTarget Target { get; set; }
+ // 是否允许临时恢复最小化窗口再截:默认 false,必须由操作者在设置里显式授权。
///
/// Temporarily restoring a minimized window makes it flash on screen and changes the foreground.
/// It never happens unless the operator authorizes it in the settings.
///
public bool AllowRestoreMinimized { get; set; }
+ // 临时恢复最小化后等待界面稳定再截的毫秒数。
public int RestoreSettleMs { get; set; }
+ // 是否允许最后用屏幕拷贝兜底(需要窗口可见、未被遮挡)。
/// Screen copy needs the window to be visible; it is a last resort.
public bool AllowScreenCopyFallback { get; set; }
}
@@ -73,22 +103,30 @@ namespace pacs_win_uia.Services
/// Caller owns and must dispose the bitmap.
public Bitmap Image { get; set; }
+ // 最终成功的截图方式。
public ScreenshotMethod Method { get; set; }
+ // 实际截取区域的矩形。
public NativeRectangleInfo Bounds { get; set; }
+ // 保存到磁盘时的文件路径(未保存则为空)。
public string FilePath { get; set; }
+ // 是否成功地截到了可用图像(false 表示失败或校验未过)。
/// False when no method produced a usable image, or the image failed validation.
public bool IsComplete { get; set; }
+ // 失败原因(人类可读)。
public string FailureReason { get; set; }
+ // 每种方式各自的返回情况,便于排查(如“PrintWindowFull:图像无效(整张图只有一种颜色)”)。
/// What each method returned, for diagnosis.
public List Attempts { get; private set; }
+ // 截取时目标窗口是否处于最小化状态。
public bool WasMinimized { get; set; }
+ // 是否为了截图临时恢复过最小化窗口。
public bool WasRestoredTemporarily { get; set; }
}
@@ -96,11 +134,14 @@ namespace pacs_win_uia.Services
/// Captures windows and screen rectangles. Every method is tried in turn and the result is
/// validated: an API returning success is not proof of a usable image, so a blank or uniform
/// bitmap is reported as a failure rather than being handed on as a screenshot.
+ /// 逐个尝试各种截图方式并校验结果;空白/纯色位图按失败上报。
///
public sealed class ScreenshotService
{
+ // 有效图像的最小边长(像素);小于此尺寸一律视为不可用。
private const int MinUsefulSize = 4;
+ // 按优先级截取一个窗口(或被授权时先临时恢复最小化),返回带诊断的过程结果。
public ScreenshotResult CaptureWindow(IntPtr handle, ScreenshotOptions options)
{
if (options == null)
@@ -192,6 +233,7 @@ namespace pacs_win_uia.Services
}
/// Screen copy of an explicit rectangle: used for a control's bounding box.
+ /// 对一个显式屏幕矩形做屏幕拷贝:用于控件的包围盒(无窗口可查,只能屏幕拷贝)。
public ScreenshotResult CaptureRectangle(Rectangle bounds, ScreenshotOptions options)
{
var result = new ScreenshotResult
@@ -213,6 +255,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 用指定的 PrintWindow 标志尝试截取一次;成功且校验通过才把图像写进 result。
private static void TryCaptureWith(
uint flags,
ScreenshotMethod method,
@@ -283,6 +326,7 @@ namespace pacs_win_uia.Services
}
}
+ // 从窗口 DC 做 BitBlt 截图;客户区模式会按边框偏移取源,避免事后裁剪掉边框。
private static void TryBitBlt(IntPtr handle, Rectangle bounds, ScreenshotOptions options, ScreenshotResult result)
{
Bitmap bitmap = null;
@@ -374,6 +418,7 @@ namespace pacs_win_uia.Services
}
}
+ // 屏幕拷贝兜底:直接抄屏幕像素;窗口被遮挡时会抄到遮挡物。
private static void TryScreenCopy(Rectangle bounds, ScreenshotResult result)
{
Bitmap bitmap = null;
@@ -412,6 +457,7 @@ namespace pacs_win_uia.Services
/// "Did we actually get a picture": non-empty size and more than one colour. A successful API
/// call that produced a uniformly black/white image is reported as a failure.
///
+ /// 校验“是否真的截到了图”:尺寸够大且不止一种颜色;API 成功但得到全黑/全白图也算失败。
public static bool TryValidate(Bitmap bitmap, out string reason)
{
reason = null;
@@ -471,6 +517,7 @@ namespace pacs_win_uia.Services
}
/// Saves the image and returns the path; also used for OCR evidence.
+ /// 把图像保存为 PNG 并返回路径(时间戳+标签命名);也用于 OCR 证据留存。
public static string Save(Bitmap bitmap, string directory, string tag)
{
if (bitmap == null)
@@ -488,6 +535,7 @@ namespace pacs_win_uia.Services
return path;
}
+ // 临时把最小化窗口显示出来(SW_SHOWNOACTIVATE,不抢焦点)以便截取,等待设定的稳定时间。
private static bool TryRestoreForCapture(
IntPtr handle,
Rectangle bounds,
@@ -510,6 +558,7 @@ namespace pacs_win_uia.Services
}
}
+ // 截图后把目标窗口恢复为最小化,并尽量还原原来的前台窗口(不保证完全无感)。
private static void RestoreAfterCapture(IntPtr handle, IntPtr foregroundBefore, ScreenshotResult result)
{
try
@@ -529,12 +578,14 @@ namespace pacs_win_uia.Services
}
}
+ // 返回本程序集所在目录(用于默认截图保存目录),取不到时退回当前工作目录。
private static string ExecutableDirectory()
{
string directory = Path.GetDirectoryName(typeof(ScreenshotService).Assembly.Location);
return string.IsNullOrEmpty(directory) ? Directory.GetCurrentDirectory() : directory;
}
+ // 把标签清成合法的文件名片段:去掉非法字符,超长截断到 40 字符。
private static string Sanitize(string tag)
{
if (string.IsNullOrWhiteSpace(tag))
diff --git a/src/pacs_win_uia/Services/SingleInstanceService.cs b/src/pacs_win_uia/Services/SingleInstanceService.cs
index ef8366c..d1d4212 100644
--- a/src/pacs_win_uia/Services/SingleInstanceService.cs
+++ b/src/pacs_win_uia/Services/SingleInstanceService.cs
@@ -1,3 +1,34 @@
+// =============================================================================
+// SingleInstanceService.cs —— 单实例仲裁与跨进程转发(每个用户/会话一个 owner)
+//
+// 职责:
+// 用「当前用户 + 会话」命名的 Mutex 判定谁是唯一主实例(owner),并用配套的命名管道
+// 承接其它进程发来的请求。owner 负责真正执行;非 owner 只能把请求转发过去。
+//
+// 被谁调用:
+// Program.Main 构造并调用 Start / Execute / Forward;每次命令行启动都会经过本类。
+//
+// 关键约束 / 边界条件:
+// 1. Mutex 是「线程相关」的:必须在同一线程上构造与 Dispose。
+// 2. 非 owner 永远只转发,即使连接失败也绝不把自己提升为实例(绝不本地另起实例)。
+// 3. 只有两种方式成为 owner:启动时空闲取得锁,或前一个进程崩溃后取得被遗弃的锁
+// (AbandonedMutexException)。
+// 4. Mutex 与管道都只允许「当前用户」访问,并显式拒绝其它会话(NetworkSid 拒绝)。
+//
+// 管道消息帧格式:
+// 4 字节小端长度(JSON 的字节数)+ JSON 正文(DataContractJsonSerializer)。
+// 请求上限 256 KB,响应上限 64 MB。
+//
+// 退出顺序(为什么先停管道再释放 Mutex):
+// Dispose 先取消 _shutdown 让监听与在途客户端收尾,WaitAll 等请求全部结束后,最后才
+// 释放 Mutex。顺序不能反:一旦先放锁,别的进程会立刻成为新 owner 开始接请求,而旧
+// owner 可能还在写同一个输出文件,造成并发写坏/覆盖。
+//
+// 要改什么就改哪里:
+// 消息大小上限 -> MaxRequestBytes / MaxResponseBytes。
+// 传输超时 -> TransportTimeoutMs。
+// 管道名 / ACL -> 构造函数与 CreateServer。
+// =============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -15,6 +46,7 @@ using pacs_win_uia.Diagnostics;
namespace pacs_win_uia.Services
{
+ // 单实例服务:每个「用户+会话」只有一个 owner;本类同时负责仲裁与请求转发。
///
/// One owner per Windows user/session, including one-shot headless invocations.
/// Construct and dispose on the same thread (Windows mutex ownership is thread-affine).
@@ -22,21 +54,37 @@ namespace pacs_win_uia.Services
///
internal sealed class SingleInstanceService : IDisposable
{
+ // 建立连接/发送/接收的超时(毫秒)。
private const int TransportTimeoutMs = 15000;
+ // 单次请求帧的字节上限(256 KB)。
private const int MaxRequestBytes = 256 * 1024;
+ // 单次响应帧的字节上限(64 MB,读取报告可能很大)。
private const int MaxResponseBytes = 64 * 1024 * 1024;
+ // 单实例互斥锁:Local\ 前缀表示仅当前会话;命名中含用户 SID 与会话 ID。
private readonly Mutex _mutex;
+ // 命名管道名:与互斥锁同名,保证同一用户/会话对应同一管道。
private readonly string _pipeName;
+ // 当前用户的 SID,用于管道/互斥锁 ACL 与转发校验。
private readonly SecurityIdentifier _user;
+ // 当前进程所在的 Windows 会话 ID;用于拒绝跨会话请求。
private readonly int _sessionId;
+ // 取消信号:Dispose 时触发,令监听循环与在途客户端任务退出。
private readonly CancellationTokenSource _shutdown = new CancellationTokenSource();
+ // 读取请求的串行闸门:同一时刻只让一个「读取」执行,避免并发写同一输出文件。
private readonly SemaphoreSlim _readGate = new SemaphoreSlim(1, 1);
+ // 保护 _clients 列表的锁。
private readonly object _clientsLock = new object();
+ // 在途的客户端处理任务,Dispose 时等待它们结束。
private readonly List _clients = new List();
+ // 后台监听任务。
private Task _listener;
+ // 请求处理器(由 Main 注入):真正执行请求并返回退出码。
private Func _handler;
+ // 是否已释放。
private bool _disposed;
+ // 构造时即尝试取得 Mutex:拿到即 owner,拿不到即只能转发。
+ // 同时确定当前用户 SID 与会话 ID,拼出 Mutex/管道名。
public SingleInstanceService()
{
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
@@ -70,33 +118,42 @@ namespace pacs_win_uia.Services
}
}
+ // 本进程是否为主实例:true=负责真正执行;false=只能转发。
public bool IsOwner { get; private set; }
+ // 转发请求的载荷(跨进程 JSON 传输)。
[DataContract]
public sealed class Request
{
+ // 命令行参数;其中的路径已由调用方在跨进程前解析为绝对路径。
// Explicit path arguments are made absolute by the caller, before crossing processes.
[DataMember(Order = 1, IsRequired = true)]
public string[] Arguments { get; set; }
+ // 默认输出路径;属于「启动方」的 exe 目录,不一定是 owner 的目录。
// Defaults belong to the launching executable, not necessarily the owner's directory.
[DataMember(Order = 2, IsRequired = true)]
public string DefaultOutputPath { get; set; }
}
+ // owner 回传的结果:标准输出/标准错误/退出码,由转发方原样交给调用进程。
[DataContract]
public sealed class Response
{
+ // owner 执行期间写入标准输出的内容。
[DataMember(Order = 1, IsRequired = true)]
public string StandardOutput { get; set; }
+ // owner 执行期间写入标准错误的内容。
[DataMember(Order = 2, IsRequired = true)]
public string StandardError { get; set; }
+ // owner 的执行退出码(0/1/2,见 Program)。
[DataMember(Order = 3, IsRequired = true)]
public int ExitCode { get; set; }
}
+ // 启动管道服务:立即开始接受连接;管道 I/O 与处理器都不在 UI 线程上运行。
/// Starts accepting immediately; neither pipe I/O nor handlers run on the UI thread.
public void Start(Func handler)
{
@@ -109,6 +166,8 @@ namespace pacs_win_uia.Services
_listener = Task.Run(() => AcceptLoopAsync(first));
}
+ // owner 直接执行一个请求(首个无界面实例也要用它)。
+ // 读取类请求经 _readGate 串行(含其输出文件),但「激活窗口」类请求不等待长读取。
///
/// Also used by the first headless invocation. Serialize reads (including their output files),
/// but do not make an activation request wait for a long-running read.
@@ -136,6 +195,8 @@ namespace pacs_win_uia.Services
}
}
+ // 非 owner 把请求发给现有 owner,并取回响应(转发语义)。
+ // 只在「建立连接」阶段重试;请求一旦发出就不重试:丢失响应无法证明 owner 没写过输出文件。
///
/// Retry only connection establishment during startup. After sending a request, never retry it:
/// losing a reply does not prove that the owner did not already read or write the output file.
@@ -198,6 +259,7 @@ namespace pacs_win_uia.Services
}
}
+ // 探测已有实例是否还活着:能瞬间拿到 Mutex 说明它已退出(拿到后立刻放掉)。
private bool OwnerStillRunning()
{
bool acquired;
@@ -213,6 +275,7 @@ namespace pacs_win_uia.Services
return !acquired;
}
+ // 创建服务端管道实例:ACL 只允许当前用户,显式拒绝 NetworkSid(其它会话)。
private NamedPipeServerStream CreateServer()
{
var security = new PipeSecurity();
@@ -225,6 +288,8 @@ namespace pacs_win_uia.Services
PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 4096, 4096, security);
}
+ // 监听循环:等待连接 -> 交给客户端任务处理 -> 再建一个新管道继续等待。
+ // 每次只把「当前」管道(而非循环变量)交给客户端,避免与新管道混淆。
private async Task AcceptLoopAsync(NamedPipeServerStream pipe)
{
try
@@ -263,6 +328,8 @@ namespace pacs_win_uia.Services
}
}
+ // 处理单个客户端连接:校验同会话 -> 读请求 -> 执行 -> 回写响应。
+ // 连接损坏或帧非法只记日志,绝不允许影响监听循环与界面。
private async Task HandleClientAsync(NamedPipeServerStream pipe)
{
using (pipe)
@@ -327,6 +394,7 @@ namespace pacs_win_uia.Services
}
}
+ // 校验某个 PID 是否与本实例同属一个 Windows 会话;进程不存在/无权访问时视为不同会话。
private bool IsSameSession(uint processId)
{
try
@@ -341,6 +409,7 @@ namespace pacs_win_uia.Services
catch (System.ComponentModel.Win32Exception) { return false; }
}
+ // 校验请求合法性:参数数组非空且无 null 项,默认输出路径必须是非空的绝对路径。
private static void ValidateRequest(Request request)
{
if (request == null || request.Arguments == null || Array.Exists(request.Arguments, arg => arg == null) ||
@@ -350,6 +419,7 @@ namespace pacs_win_uia.Services
}
}
+ // 写出一个消息帧:4 字节小端长度 + JSON 正文;超过 limit 直接报错。
private static async Task WriteMessageAsync(Stream pipe, T value, int limit, CancellationToken token)
{
byte[] data;
@@ -365,6 +435,7 @@ namespace pacs_win_uia.Services
await pipe.FlushAsync(token).ConfigureAwait(false);
}
+ // 读取一个消息帧:先读 4 字节长度,再按长度读正文并反序列化;长度非法或超限报错。
private static async Task ReadMessageAsync(Stream pipe, int limit, CancellationToken token)
{
var header = new byte[4];
@@ -379,6 +450,7 @@ namespace pacs_win_uia.Services
}
}
+ // 读满指定字节数;读到 0 字节(对端关闭)抛 EndOfStreamException。
private static async Task ReadExactlyAsync(Stream pipe, byte[] bytes, CancellationToken token)
{
int offset = 0;
@@ -390,12 +462,14 @@ namespace pacs_win_uia.Services
}
}
+ // 只有 owner 可以执行请求;转发方调用 Execute/Start 会在此抛异常。
private void EnsureOwner()
{
if (_disposed) throw new ObjectDisposedException(GetType().Name);
if (!IsOwner) throw new InvalidOperationException("只有主实例可以执行请求。");
}
+ // 尽力关闭管道:已关闭或正在关闭的异常都被吞掉,不能让清理路径抛错。
private static void ClosePipe(Stream pipe)
{
try { pipe.Dispose(); }
@@ -403,6 +477,8 @@ namespace pacs_win_uia.Services
catch (ObjectDisposedException) { }
}
+ // 释放顺序:先 _shutdown.Cancel() 停监听、等在途客户端结束,最后才释放 Mutex 并释放资源。
+ // 必须先停管道再放锁(原因见文件顶部「退出顺序」)。
public void Dispose()
{
if (_disposed) return;
@@ -426,14 +502,17 @@ namespace pacs_win_uia.Services
}
}
+ // 取命名管道服务端进程 PID(用于转发方校验对端会话)。
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out uint serverProcessId);
+ // 取命名管道客户端进程 PID(用于服务端校验对端会话)。
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetNamedPipeClientProcessId(SafePipeHandle pipe, out uint clientProcessId);
+ // 把本进程的前台激活权限临时授予 owner,使 owner 能弹到前台。
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllowSetForegroundWindow(uint processId);
diff --git a/src/pacs_win_uia/Services/TargetProbeService.cs b/src/pacs_win_uia/Services/TargetProbeService.cs
index 7f0d96a..36b75b1 100644
--- a/src/pacs_win_uia/Services/TargetProbeService.cs
+++ b/src/pacs_win_uia/Services/TargetProbeService.cs
@@ -6,6 +6,24 @@ using pacs_win_uia.Diagnostics;
using pacs_win_uia.Interop;
using pacs_win_uia.Models;
+// ============================================================================
+// TargetProbeService.cs —— 把 Win32 / UIA / MSAA 三种点探测合并成一个只读结果
+// 职责:给定屏幕坐标,按固定顺序探测光标下的目标控件,给出尽可能细的包围盒与来源。
+// 拾取下钻顺序(重要):
+// 1) Win32:WindowFromPoint 后 DescendToDeepestChild 逐层下钻到最深子窗口——
+// 这是唯一不会阻塞的本地调用,永远能给出一个目标窗口(浏览器外壳的渲染窗口就是子 HWND)。
+// 2) UIA:从 Win32 命中的顶层窗口出发按点取元素,并校验是否隶属同一窗口树;若 UIA 只返回整窗
+// (ControlType.Window,浏览器外壳常见),不结束搜索,继续走 MSAA,避免把整窗高亮成控件。
+// 3) MSAA:在 Win32 已解析出的最深窗口上做 accHitTest(该对象更了解自己的子对象),
+// 失败再退回全局 AccessibleObjectFromPoint;跨进程结果会被拒绝合并。
+// 最后取“更小”的矩形作为包围盒(UseIfSmaller),让高亮落在控件而非整窗。
+// 单飞与看门狗 / 时限:ProbeAsync 用 LongRunning 线程跑同步探测(卡住的提供者不能永久占用线程池);
+// 调用方另有 1.2 秒硬期限与 ProbeWindowOnly 的纯 Win32 兜底(见 CrosshairPicker)。
+// 要改什么就改哪里:
+// - 探测顺序 / 合并规则:Probe、UseIfSmaller、TryMsaaHitTest。
+// - 下钻深度与跳过规则:DescendToDeepestChild、MaxDescendDepth。
+// - 纯 Win32 快路径:ProbeWindowOnly。
+// ============================================================================
namespace pacs_win_uia.Services
{
///
@@ -15,13 +33,19 @@ namespace pacs_win_uia.Services
///
public sealed class TargetProbeService
{
+ // 子窗口下钻的最大深度,防止异常窗口树导致死循环。
private const int MaxDescendDepth = 16;
+ // 只读窗口快照服务(Win32 层)。
private readonly NativeWindowService _windowService;
+ // UIA 探测服务。
private readonly UiAutomationService _uiAutomationService;
+ // MSAA 探测服务。
private readonly MsaaService _msaaService;
+ // 本工具自身进程 ID,用于识别并排除自身窗口。
private readonly int _ownProcessId;
+ // 便捷构造:使用默认的 MsaaService。
public TargetProbeService(
NativeWindowService windowService,
UiAutomationService uiAutomationService,
@@ -30,6 +54,7 @@ namespace pacs_win_uia.Services
{
}
+ // 全量注入;依赖为空即抛 ArgumentNullException。
public TargetProbeService(
NativeWindowService windowService,
UiAutomationService uiAutomationService,
@@ -42,11 +67,13 @@ namespace pacs_win_uia.Services
_ownProcessId = ownProcessId;
}
+ // 便捷重载:不预知窗口句柄,由坐标自己查。
public PointPickResult Probe(Point screenPoint)
{
return Probe(screenPoint, IntPtr.Zero);
}
+ // 主探测:Win32 → UIA → MSAA 依次尝试,合并成只读的 PointPickResult。
public PointPickResult Probe(Point screenPoint, IntPtr knownWindowHandle)
{
var result = new PointPickResult { ScreenPoint = screenPoint };
@@ -140,6 +167,7 @@ namespace pacs_win_uia.Services
/// Keeps the tightest rectangle available: a pick should mark the control under the pointer,
/// not the whole window it belongs to.
///
+ /// 只保留更紧的矩形:拾取应标出光标下的控件,而不是它所属的整个窗口。
private static void UseIfSmaller(PointPickResult result, NativeRectangleInfo candidate)
{
if (candidate == null || !candidate.IsValid)
@@ -161,6 +189,7 @@ namespace pacs_win_uia.Services
}
}
+ // MSAA 命中测试:优先在 Win32 找到的最深窗口上做,失败再退回全局点查询;跨进程结果拒绝合并。
private void TryMsaaHitTest(Point screenPoint, PointPickResult result)
{
try
@@ -218,6 +247,7 @@ namespace pacs_win_uia.Services
/// Used when a UIA probe does not come back in time (an unresponsive provider must not be
/// able to keep the picker open forever).
///
+ /// 纯 Win32 解析:不调 UIA/MSAA,所以总能很快返回,用于 UIA 探测超时时的兜底。
public PointPickResult ProbeWindowOnly(Point screenPoint, IntPtr knownWindowHandle)
{
var result = new PointPickResult { ScreenPoint = screenPoint };
@@ -251,6 +281,7 @@ namespace pacs_win_uia.Services
/// ChildWindowFromPointEx takes coordinates relative to the parent's client area, so the point
/// is converted at every level.
///
+ /// 沿子窗口链下钻到包含该点的最深窗口(浏览器外壳的渲染窗口就是真子 HWND,靠它进入内部)。
private static IntPtr DescendToDeepestChild(IntPtr handle, Point screenPoint)
{
IntPtr current = handle;
@@ -291,6 +322,7 @@ namespace pacs_win_uia.Services
return current;
}
+ // 异步探测:在独立 LongRunning 线程上跑同步 Probe(卡死的提供者不会永久占用线程池容量)。
public Task ProbeAsync(
Point screenPoint,
CancellationToken cancellationToken,
diff --git a/src/pacs_win_uia/Services/UiAutomationService.cs b/src/pacs_win_uia/Services/UiAutomationService.cs
index ad79568..b8aeb4b 100644
--- a/src/pacs_win_uia/Services/UiAutomationService.cs
+++ b/src/pacs_win_uia/Services/UiAutomationService.cs
@@ -1,3 +1,25 @@
+// =============================================================================
+// UiAutomationService —— UIA 活动对象 → 可序列化快照 的转换层(绝不调用任何 Pattern 动作)。
+// 职责:
+// 1) CreateSnapshotCache:用单个 CacheRequest 一次性请求所有需要的属性+模式,把它挂到遍历上后,
+// “每节点 ~25 次跨进程 RPC”被压成“每节点 1 次”——大控件树(UWP/Qt/Chromium)从数秒降到可用。
+// 2) 统一用 RawView(RawViewCondition/RawViewWalker),包含不可见元素与非控件元素,与控件树显示一致。
+// 3) InspectCached 只读缓存(零 provider 调用;缓存未命中按设计抛异常,回退实时读取 Inspect)。
+// 4) FromPoint / FromHandleAtPoint 命中 + 祖先校验;FromHandleAtPoint 有明确的 fallback 规则。
+// 5) ReadSupportedPatterns 做 Pattern 探测与命名规范化(XxxPatternIdentifiers.Pattern → XxxPattern)。
+// 被谁调用:UI/MainForm.cs(拾取、检查、导出)与 Services/ControlTreeService.ReadUia(树读取)。
+// 线程模型:AutomationElement 的每次读取都是跨进程 RPC,会阻塞在无响应目标上。树读取必须跑在
+// MainForm 的 LongRunning 专用线程;CacheRequest.Activate/Pop 作用于“当前线程”,所以整个遍历
+// 必须在同一线程内 activate→读→pop(见 ReadTree 的 try/finally)。取消/超时用 ReadBudget 在
+// 调用间隙检查——在途 RPC 无法中断。命中测试的 FindDeepestElementAtPoint 另有 3 秒/节点数上限,
+// 避免回退路径慢到失控。
+// 要改什么就改哪里:
+// - 新增要快照的属性/模式 → KnownPatterns 与 CreateSnapshotCache(两处必须同步)。
+// - 改命中与祖先判定 → FromPoint / FromHandleAtPoint / BelongsToWindow。
+// - 改 UWP/浏览器内层窗口识别 → FindNestedContentWindow / IsContentHost。
+// - 改树遍历 → ReadTree / ReadNode。
+// =============================================================================
+
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -17,6 +39,7 @@ namespace pacs_win_uia.Services
///
public sealed class UiAutomationService
{
+ // 工具已知的 UIA 模式清单:既是缓存请求项,也是 Pattern 命名规范化用的字典。
private static readonly PatternDescriptor[] KnownPatterns =
{
new PatternDescriptor("ValuePattern", ValuePattern.Pattern),
@@ -36,6 +59,7 @@ namespace pacs_win_uia.Services
new PatternDescriptor("MultipleViewPattern", MultipleViewPattern.Pattern)
};
+ // 构建“一次请求全部属性+模式”的 CacheRequest —— 性能的根本手段。
///
/// One cache request covering every property and pattern a snapshot needs. Applied to the
/// tree walker, it turns ~25 cross-process calls per node into one: without it a large tree
@@ -65,6 +89,7 @@ namespace pacs_win_uia.Services
return request;
}
+ // 只读缓存做快照;缓存未命中则回退 Inspect(实时读取)。
///
/// Snapshot from cached values: no provider calls at all. Falls back to live reads when the
/// element was not obtained under the request (a cache miss throws by design).
@@ -123,6 +148,7 @@ namespace pacs_win_uia.Services
}
}
+ // 由 HWND 构造 AutomationElement 后实时快照。
public UiaElementInfo FromHandle(IntPtr handle)
{
if (handle == IntPtr.Zero)
@@ -140,6 +166,7 @@ namespace pacs_win_uia.Services
}
}
+ // 广度优先(≤3 层、≤100 节点)查找真正承载内容的内层窗口。
///
/// The nested window element that actually hosts an app's content, if any. A UWP window
/// (ApplicationFrameWindow -> Windows.UI.Core.CoreWindow) and a browser shell both expose the
@@ -194,6 +221,7 @@ namespace pacs_win_uia.Services
return IntPtr.Zero;
}
+ // 判定内层窗口是否 XAML/UIA/CoreWindow/Chromium 内容宿主。
/// XAML / UIA providers only; a nested Win32 window is usually chrome, not content.
private static bool IsContentHost(AutomationElement.AutomationElementInformation info)
{
@@ -208,6 +236,7 @@ namespace pacs_win_uia.Services
className.IndexOf("Chrome_RenderWidgetHost", StringComparison.OrdinalIgnoreCase) >= 0;
}
+ // 全屏坐标命中快照(AutomationElement.FromPoint)。
public UiaElementInfo FromPoint(Point point)
{
try
@@ -220,6 +249,7 @@ namespace pacs_win_uia.Services
}
}
+ // 限定在某窗口内命中:先 FromPoint+祖先校验,失败再用 RawView 深搜回退。
public UiaElementInfo FromHandleAtPoint(IntPtr handle, Point point)
{
if (handle == IntPtr.Zero) return Failure("HWND 为空。");
@@ -247,6 +277,7 @@ namespace pacs_win_uia.Services
catch (Exception ex) { return Failure(FormatException(ex)); }
}
+ // 祖先校验:用引用相等或 HWND 相等判断命中元素属于目标窗口,绝不用名称/类名。
private static bool BelongsToWindow(AutomationElement hit, AutomationElement root, IntPtr handle)
{
AutomationElement current = hit;
@@ -266,14 +297,22 @@ namespace pacs_win_uia.Services
return false;
}
+ // 命中回退的状态:节点预算 + 3 秒时钟,记录当前最优(面积最小、其次最深)。
private sealed class PointProbeState
{
+ // 初始化剩余节点预算。
internal PointProbeState(int maximumNodes) { Remaining = maximumNodes; }
+ // 剩余可探测节点数。
internal int Remaining { get; private set; }
+ // 目前命中的最优元素。
internal AutomationElement Best;
+ // 最优元素的面积(越小越贴合)。
internal double BestArea = double.PositiveInfinity;
+ // 最优元素的深度。
internal int BestDepth = -1;
+ // 命中回退的 3 秒总时限。
private readonly System.Diagnostics.Stopwatch _clock = System.Diagnostics.Stopwatch.StartNew();
+ // 消耗一个预算;超时或耗尽返回 false,以停止下钻。
internal bool Consume()
{
if (Remaining <= 0 || _clock.Elapsed > TimeSpan.FromSeconds(3)) return false;
@@ -282,6 +321,7 @@ namespace pacs_win_uia.Services
}
}
+ // RawView 深搜找包含该点的最小元素;预算只在调用点消耗,递归进来后不要再重复消耗。
private static void FindDeepestElementAtPoint(AutomationElement element, Point point, int depth,
int maxDepth, PointProbeState state)
{
@@ -318,6 +358,7 @@ namespace pacs_win_uia.Services
catch (Exception) { /* Keep the best actual hit, never an unrelated root fallback. */ }
}
+ // 生成“元素+祖先链”的紧凑诊断文本(有界、只读、异常安全,只喂日志)。
///
/// Compact structural description of an element and its ancestors, for console diagnostics.
/// Bounded, read-only and exception-safe: it only ever feeds the log.
@@ -343,6 +384,7 @@ namespace pacs_win_uia.Services
return lines;
}
+ // 生成“直接子元素”的紧凑诊断文本。
/// Compact description of an element's direct children, for console diagnostics.
public IList DescribeChildren(AutomationElement element, int maxChildren)
{
@@ -394,6 +436,7 @@ namespace pacs_win_uia.Services
return lines;
}
+ // 单个元素的紧凑描述(含模式与子元素计数)。
private static string DescribeElement(AutomationElement element, int maxChildren)
{
string description;
@@ -454,6 +497,7 @@ namespace pacs_win_uia.Services
return description;
}
+ // 探测单个模式是否存在,读取异常时记为“名字?”。
private static void ProbePattern(AutomationElement element, AutomationPattern pattern, string name, ICollection names)
{
try
@@ -470,6 +514,7 @@ namespace pacs_win_uia.Services
}
}
+ // 实时读取元素快照(每个属性独立调用,异常进 PropertyErrors)。
public UiaElementInfo Inspect(AutomationElement element)
{
var snapshot = new UiaElementInfo
@@ -514,6 +559,7 @@ namespace pacs_win_uia.Services
return snapshot;
}
+ // 以 AutomationElement 为根读取整棵树;activate 缓存 → 读 → pop。
public UiaTreeNodeInfo ReadTree(
AutomationElement root,
int maxDepth,
@@ -549,6 +595,7 @@ namespace pacs_win_uia.Services
}
}
+ // 以 HWND 为根读取整棵树;同样 activate 缓存 → 读 → pop。
public UiaTreeNodeInfo ReadTree(
IntPtr handle,
int maxDepth,
@@ -594,6 +641,7 @@ namespace pacs_win_uia.Services
}
}
+ // 递归读取一个节点:RawView 批量取子,配合缓存让每个子节点零属性往返。
private UiaTreeNodeInfo ReadNode(
AutomationElement element,
int depth,
@@ -687,6 +735,7 @@ namespace pacs_win_uia.Services
return node;
}
+ // 校验 maxDepth/maxNodes 参数。
private static void ValidateTreeArguments(int maxDepth, int maxNodes)
{
if (maxDepth < 0)
@@ -700,6 +749,7 @@ namespace pacs_win_uia.Services
}
}
+ // 用探测结果整体替换 snapshot 的模式列表。
private static void ReplacePatterns(UiaElementInfo snapshot, IList patterns)
{
snapshot.SupportedPatterns.Clear();
@@ -709,6 +759,7 @@ namespace pacs_win_uia.Services
}
}
+ // 取支持模式并规范化名称;只有在 provider 返回空时才逐项探测(省跨进程调用)。
private static List ReadSupportedPatterns(AutomationElement element, UiaElementInfo snapshot)
{
var names = new List();
@@ -764,6 +815,7 @@ namespace pacs_win_uia.Services
return names;
}
+ // 把 “XxxPatternIdentifiers.Pattern” 规范成 “XxxPattern”。
///
/// Turns a raw programmatic name such as "TransformPatternIdentifiers.Pattern" into the
/// readable "TransformPattern" that the other pattern names use.
@@ -781,6 +833,7 @@ namespace pacs_win_uia.Services
: name;
}
+ // 即时取 RuntimeId(惰性,保存监控项时才用到)。
private static string ReadRuntimeId(AutomationElement element, UiaElementInfo snapshot)
{
try
@@ -795,6 +848,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全读取 ControlType(失败返回 null 并记错)。
private static string ReadControlType(Func getter, UiaElementInfo snapshot)
{
try
@@ -809,6 +863,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全读取字符串属性。
private static string ReadString(Func getter, UiaElementInfo snapshot, string propertyName)
{
try
@@ -822,6 +877,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全读取整型属性(失败返回 0 并记错)。
private static int ReadInt32(Func getter, UiaElementInfo snapshot, string propertyName)
{
try
@@ -835,6 +891,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全读取布尔属性(失败返回 null 并记错)。
private static bool? ReadBoolean(Func getter, UiaElementInfo snapshot, string propertyName)
{
try
@@ -848,6 +905,7 @@ namespace pacs_win_uia.Services
}
}
+ // 安全读取矩形(失败返回空矩形并记错)。
private static NativeRectangleInfo ReadRectangle(Func getter, UiaElementInfo snapshot, string propertyName)
{
try
@@ -861,6 +919,7 @@ namespace pacs_win_uia.Services
}
}
+ // Rect → NativeRectangleInfo;空/无穷/越界一律转成空矩形。
private static NativeRectangleInfo ToRectangleInfo(System.Windows.Rect rectangle)
{
if (rectangle.IsEmpty || double.IsInfinity(rectangle.Left) || double.IsInfinity(rectangle.Top) ||
@@ -878,6 +937,7 @@ namespace pacs_win_uia.Services
(int)Math.Round(rectangle.Bottom));
}
+ // 构造一个 IsAvailable=false 的失败快照。
private static UiaElementInfo Failure(string error)
{
return new UiaElementInfo
@@ -887,6 +947,7 @@ namespace pacs_win_uia.Services
};
}
+ // 统一异常文本(ElementNotAvailable 特殊化,COM 异常带 HResult)。
private static string FormatException(Exception exception)
{
if (exception is ElementNotAvailableException)
@@ -902,15 +963,19 @@ namespace pacs_win_uia.Services
return exception.GetType().Name + ": " + exception.Message;
}
+ // 模式名与其 AutomationPattern 的配对。
private sealed class PatternDescriptor
{
+ // 记录可读名与模式对象。
internal PatternDescriptor(string name, AutomationPattern pattern)
{
Name = name;
Pattern = pattern;
}
+ // 规范化的模式名。
internal string Name { get; private set; }
+ // UIA 模式对象。
internal AutomationPattern Pattern { get; private set; }
}
}
diff --git a/src/pacs_win_uia/Services/Win32TreeReader.cs b/src/pacs_win_uia/Services/Win32TreeReader.cs
index db4546e..fc29491 100644
--- a/src/pacs_win_uia/Services/Win32TreeReader.cs
+++ b/src/pacs_win_uia/Services/Win32TreeReader.cs
@@ -1,3 +1,17 @@
+// =============================================================================
+// Win32TreeReader —— 三种来源里的“兜底地板”。
+// 职责:用 EnumChildWindows 拿到根窗口的全部后代 HWND(含孙辈),再用 GA_PARENT 重建父子层级,
+// 抓类名/矩形/可见性/进程名,产出 ControlTreeNode(Source=Win32) 快照。
+// 被谁调用:Services/ControlTreeService.ReadOne(自动模式最后一道)。
+// 线程模型:EnumChildWindows / GetWindowInfo / GetClassName / IsWindow 都是本地调用,不进入目标进程,
+// 所以即使目标无响应也不会卡住;唯一跨进程的是窗口标题 WM_GETTEXT,故走 SendMessageTimeout
+// (SMTO_ABORTIFHUNG)+短超时,且只对可见窗口读取。整个读取仍跑在 UI/MainForm.cs 的 LongRunning
+// 线程上,是“不会挂”的保险来源。
+// 要改什么就改哪里:
+// - 改窗口信息采集 → CaptureWindow。
+// - 改标题读取开关/超时 → Models 的 ControlTreeOptions.TitleReadTimeoutMs / ReadWindowTitles。
+// =============================================================================
+
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
@@ -9,6 +23,7 @@ using pacs_win_uia.Models;
namespace pacs_win_uia.Services
{
+ // Win32 兜底读树:本地枚举全部后代 HWND,不依赖目标进程响应。
///
/// The guaranteed floor of the three sources: every descendant HWND of the root, with class name
/// and rectangles. EnumChildWindows is a local call and does not touch the target process, so this
@@ -19,9 +34,11 @@ namespace pacs_win_uia.Services
///
public sealed class Win32TreeReader
{
+ // 消息窗口(message-only)的父句柄,遍历时跳过这类窗口。
/// HWND_MESSAGE: parent of message-only windows, which are never shown.
private static readonly IntPtr HwndMessage = new IntPtr(-3);
+ // 枚举全部后代、按 GA_PARENT 重建层级并返回 Win32 树;无子窗口不算错误。
public ControlTreeNode Read(IntPtr rootHandle, ControlTreeOptions options, CancellationToken cancellationToken)
{
if (options == null)
@@ -123,6 +140,7 @@ namespace pacs_win_uia.Services
return root;
}
+ // 按预先算好的 childrenByParent 递归建树;每个 child 先过预算闸门(超时/取消即中止)。
private static void BuildChildren(
ControlTreeNode parentNode,
IntPtr parentHandle,
@@ -190,6 +208,7 @@ namespace pacs_win_uia.Services
}
}
+ // 采集单个 HWND 的几何/样式/类名/进程;一次 GetWindowInfo 取代多次矩形/样式读取。
///
/// One GetWindowInfo call replaces GetWindowRect + GetClientRect + ClientToScreen + style
/// reads; only the class name and the (bounded) title are separate.
@@ -280,6 +299,7 @@ namespace pacs_win_uia.Services
return result;
}
+ // 跨进程读标题:SMTO_ABORTIFHUNG+短超时,目标无响应时放弃并记错误。
///
/// WM_GETTEXT is a cross-process message: a hung target would block it forever, so it is sent
/// with SMTO_ABORTIFHUNG and a short timeout.
@@ -320,6 +340,7 @@ namespace pacs_win_uia.Services
}
}
+ // 判定 message-only 窗口(父为 HWND_MESSAGE 或类名 "Message"),遍历时跳过。
private static bool IsMessageOnly(IntPtr handle)
{
IntPtr parent = NativeMethods.GetAncestor(handle, NativeMethods.GA_PARENT);
@@ -337,6 +358,7 @@ namespace pacs_win_uia.Services
return false;
}
+ // 判定 DWM cloaked(UWP/ApplicationFrameHost 看起来可见实为隐藏)。
private static bool IsCloaked(IntPtr handle)
{
try
diff --git a/src/pacs_win_uia/Services/WindowMatcher.cs b/src/pacs_win_uia/Services/WindowMatcher.cs
index c0567ac..905e525 100644
--- a/src/pacs_win_uia/Services/WindowMatcher.cs
+++ b/src/pacs_win_uia/Services/WindowMatcher.cs
@@ -1,3 +1,19 @@
+// ============================================================================
+// WindowMatcher.cs —— 窗口「分级匹配」
+// 职责:拿「进程名 / 窗口类名 / 标题关键词」三件套,在一批顶层窗口里挑出最佳匹配窗口。
+// 被谁调用:
+// · 控件定位(按保存的三件套重新找到目标窗口);
+// · 悬浮条显示条件(FloatingBarManager 判定锚定窗口;SettingsForm 的「检测显示条件」)。
+// 为什么要分级:目标程序升级后保存的窗口类名可能变(WinForms 类名里带 build 哈希),
+// 标题关键词也可能随数据显示内容而变化;所以较窄的规则匹配失败时不能整条查找都失败,
+// 而是逐级放宽。
+// 匹配级别(精确 → 宽松):
+// 4 = 进程名 + 窗口类名 + 标题关键词
+// 3 = 进程名 + 窗口类名
+// 2 = 进程名 + 标题关键词
+// 1 = 只有进程名
+// 类名为何优先于标题:只能保留一个线索时保留类名,因为类名比标题更具区分度。
+// ============================================================================
using System;
using System.Collections.Generic;
using pacs_win_uia.Models;
@@ -6,11 +22,14 @@ namespace pacs_win_uia.Services
{
public sealed class WindowMatch
{
+ // 最终选中的窗口。
public NativeWindowInfo Window { get; set; }
+ // 命中的匹配级别(4 最精确 … 1 最宽松);界面用它解释「为什么匹配到这条窗口」。
/// 4 = process+class+title, 3 = process+class, 2 = process+title, 1 = process only.
public int Level { get; set; }
+ // 该级别下的候选窗口数量;>1 表示存在歧义(只取第一个)。
public int CandidateCount { get; set; }
}
@@ -22,8 +41,11 @@ namespace pacs_win_uia.Services
///
public static class WindowMatcher
{
+ // 最高匹配级别数(4);FindBest 从 4 递减到 1 逐级尝试。
public const int Levels = 4;
+ // 入口:从最精确的级别 4 开始逐级放宽,返回第一个「有候选」的级别中的第一个窗口;
+ // 所有级别都落空则返回 null(调用方据此判定「找不到目标窗口」)。
public static WindowMatch FindBest(
IList windows,
string processName,
@@ -63,6 +85,8 @@ namespace pacs_win_uia.Services
return null;
}
+ // 判定单个窗口是否满足指定级别:进程名大小写不敏感,类名区分大小写,标题为「包含且忽略大小写」。
+ // 级别 1 在没有进程名时,已填写的其它线索仍然必须全部满足(见下方 default 分支)。
///
/// Level 4 = process+class+title, 3 = process+class, 2 = process+title, 1 = process only.
/// Class ranks above title when only one can be kept: class names are far more distinctive.
@@ -109,6 +133,7 @@ namespace pacs_win_uia.Services
}
}
+ // 把级别翻译成界面上显示的中文说明(悬浮条「检测显示条件」结果里用)。
public static string DescribeLevel(int level)
{
switch (level)
diff --git a/src/pacs_win_uia/Services/WindowVisibility.cs b/src/pacs_win_uia/Services/WindowVisibility.cs
index 7e4311f..e00f33a 100644
--- a/src/pacs_win_uia/Services/WindowVisibility.cs
+++ b/src/pacs_win_uia/Services/WindowVisibility.cs
@@ -1,3 +1,38 @@
+// ============================================================================
+// WindowVisibility —— “窗口在屏幕上还剩多少可见面积”的算法与诊断文案
+//
+// 职责:
+// 判断目标窗口/矩形是否在屏幕上可见、是否被别的窗口遮挡,并能给出“被谁挡了”的中文说明。
+//
+// 被谁调用:
+// · 运行时:FloatingBarManager.IsAnchorVisible、HighlightFollower.Tick、NodeMapOverlayForm.RefreshMap。
+// · 设置页自检(诊断模式):调用方传 ignoreOwnProcessWindows=true,让设置页能解释“运行时会不会显示”,
+// 而不因为设置窗口自己盖住目标就永远报“被遮挡”。
+//
+// 可见区域算法(TryGetVisibleRegion):
+// 1) 判定目标顶层窗口“可绘制”(可见、非最小化、非 DWM cloaked)。
+// 2) 目标区域 = GetWindowRgn(有就用真实形状;ERROR 与 NULLREGION 含义不同)或 DWM 扩展边框/Win32 边框。
+// 3) 与所有屏幕求交,裁掉屏幕外部分。
+// 4) 按 Z 序 EnumWindows:目标之前(更靠前)的每个可绘制窗口,若与结果有交就从结果里减掉并记为遮挡者;
+// 遇到目标本身即停止。
+// 5) 收尾再查一次(原生调用期间前台/最小化可能变化),结果为空则判“被完全遮挡”。
+//
+// 忽略的覆盖层:只忽略本工具已知的覆盖层窗体(见 IsToolOverlay 白名单)或显式传入的 HWND;
+// 共享 PID 本身不是忽略理由(MainForm/SettingsForm 确实会遮挡)。任意 layered 窗口的逐像素
+// alpha/色键“洞”拿不到 HRGN,因此保守地按其整个窗口区域遮挡。
+//
+// DescribeOccluders 文案含义:列出最多 4 个真正削减了可见面积的窗口;全为本工具窗口时给出
+// “这是设置页自检的正常现象”的提示;部分为本工具窗口 / 全为其他程序时分别给出处置建议。
+//
+// 两个 API 的区别与场合:
+// · TryGetVisibleRegion:返回“目标可见区域”Region 本身,调用方可继续做交/裁剪。用于需要精确
+// 可见范围的场合(如 NodeMapOverlayForm 把绘制裁剪到可见区域)以及悬浮条锚定窗口的“未被完全遮挡”判定。
+// · IsVisibleOnScreen:兼容旧调用方(无法自行裁剪画面)。返回布尔:给定屏幕矩形是否落在目标可见区域内
+// 且未被遮挡;内部调用 TryGetVisibleRegion,并用 CreateWindowRegion 排除 DWM 不可见边框/屏幕外部分,
+// 避免误报遮挡。适合“这个矩形现在看得见吗”这类简单问句。
+//
+// “要改什么就改哪里”:区域算法 → CreateWindowRegion / TryGetVisibleRegion;忽略名单 → IsToolOverlay。
+// ============================================================================
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -8,14 +43,17 @@ using pacs_win_uia.Interop;
namespace pacs_win_uia.Services
{
/// Screen-coordinate visibility regions. Returned Regions belong to the caller.
+ /// 屏幕坐标下的可见区域工具;返回的 Region 归调用方所有(用后 Dispose)。
public static class WindowVisibility
{
+ /// 窗口(取其顶层根)是否为当前前台窗口。
public static bool IsForegroundWindow(IntPtr window)
{
IntPtr root = GetRoot(window);
return root != IntPtr.Zero && root == GetRoot(NativeMethods.GetForegroundWindow());
}
+ /// 取窗口的顶层祖先(GA_ROOT);空句柄原样返回。
private static IntPtr GetRoot(IntPtr window)
{
return window == IntPtr.Zero ? IntPtr.Zero : NativeMethods.GetAncestor(window, NativeMethods.GA_ROOT);
@@ -29,6 +67,7 @@ namespace pacs_win_uia.Services
/// Per-pixel alpha/color-key holes of arbitrary layered windows are not available as HRGNs;
/// those windows conservatively occlude their window region.
///
+ /// 简化重载:不忽略自身进程窗口、不收集遮挡者列表。
public static bool TryGetVisibleRegion(IntPtr targetWindow, bool requireForeground,
IEnumerable ignoredOverlayWindows, out Region visibleRegion, out string reason)
{
@@ -45,6 +84,7 @@ namespace pacs_win_uia.Services
///
/// Optional: receives the windows that actually removed visible area, in Z order.
///
+ /// 主实现:算出目标可见区域(Z 序减去前面的窗口、屏幕裁剪),失败时给出中文原因。
public static bool TryGetVisibleRegion(IntPtr targetWindow, bool requireForeground,
IEnumerable ignoredOverlayWindows, bool ignoreOwnProcessWindows,
IList occludingWindows, out Region visibleRegion, out string reason)
@@ -137,6 +177,7 @@ namespace pacs_win_uia.Services
}
}
+ /// 窗口是否“可绘制”:可见、非最小化、未被 DWM 遮蔽(cloaked)。
private static bool IsDrawable(IntPtr window)
{
if (!NativeMethods.IsWindowVisible(window) || NativeMethods.IsIconic(window)) return false;
@@ -145,6 +186,7 @@ namespace pacs_win_uia.Services
out cloaked, sizeof(int)) != 0 || cloaked == 0;
}
+ /// 是否为本工具的覆盖层窗体(按精确类型名判断;这些不算遮挡者)。
private static bool IsToolOverlay(IntPtr window)
{
// FromHandle only resolves this process's managed controls. Use exact type names so
@@ -165,6 +207,7 @@ namespace pacs_win_uia.Services
}
/// True for windows of this process (main window, settings dialog, own overlays).
+ /// 是否属于本进程的窗口(主窗口、设置窗口、自身覆盖层)。
public static bool IsOwnProcessWindow(IntPtr window)
{
if (window == IntPtr.Zero) return false;
@@ -177,6 +220,7 @@ namespace pacs_win_uia.Services
/// Names the windows that hide the target, so "被遮挡" says by what. Chinese labels because this
/// text is shown in the settings dialog.
///
+ /// 生成“被遮挡”说明:列出最多 4 个遮挡窗口(类名+句柄+PID),并区分本工具窗口与其他程序。
public static string DescribeOccluders(IList occludingWindows, int ownProcessId,
bool ignoredOwnProcessWindows)
{
@@ -214,11 +258,13 @@ namespace pacs_win_uia.Services
return "遮挡窗口:" + list + "。请把目标窗口切到前面后重新检测。";
}
+ /// 把窗口句柄格式化成 0x… 文本。
private static string NativeWindowInfoFormat(IntPtr handle)
{
return "0x" + handle.ToInt64().ToString("X");
}
+ /// 取窗口的屏幕形状区域:优先 GetWindowRgn,否则 DWM 扩展边框,再否则 Win32 边框。
private static Region CreateWindowRegion(IntPtr window)
{
NativeMethods.RECT bounds;
@@ -249,6 +295,7 @@ namespace pacs_win_uia.Services
return new Region(bounds.ToRectangle());
}
+ /// 区域是否含有任意面积(非空)。
public static bool HasArea(Region region)
{
using (var identity = new Matrix()) return region.GetRegionScans(identity).Length != 0;
@@ -259,6 +306,7 @@ namespace pacs_win_uia.Services
/// on-screen rectangle is unobstructed. ownProcessId is retained but never exempts main/settings.
/// Unlike the node map, these older callers need not target the foreground window.
///
+ /// 兼容重载:不忽略自身进程窗口(严格模式)。
public static bool IsVisibleOnScreen(IntPtr topLevelWindow, Rectangle rect,
int ownProcessId, out string reason)
{
@@ -269,6 +317,7 @@ namespace pacs_win_uia.Services
/// Diagnostic mode only (see TryGetVisibleRegion): the tool's own windows do not count as
/// occluders, so the settings page can still explain what would happen at runtime.
///
+ /// 判断屏幕矩形是否在目标的可见窗口范围内且未被遮挡(排除 DWM 不可见边框/屏幕外部分)。
public static bool IsVisibleOnScreen(IntPtr topLevelWindow, Rectangle rect,
int ownProcessId, bool ignoreOwnProcessWindows, out string reason)
{
diff --git a/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs b/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs
index 770e2dc..a3a39c3 100644
--- a/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs
+++ b/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs
@@ -10,10 +10,39 @@ using pacs_win_uia.Diagnostics;
using pacs_win_uia.Models;
using pacs_win_uia.Services;
+/*
+ * ControlMonitorEditorControl —— 控件监控定义编辑器(列表)。
+ * 职责:维护“哪个控件、在哪个页面、映射到哪个内容键”的定义:定位方式(三来源)、读取属性
+ * (valueKey)、超时与别名等,并负责定位到控件、刷新焦点状态、校验与保存。
+ * 被谁调用:MainForm(new ControlMonitorEditorControl())——它用 SetCurrentNode 喂入当前选中节点,
+ * 并订阅 DefinitionSelected / ControlLocated / StatusChanged 三个事件。
+ * 列结构(顺序固定,见 Column* 常量):
+ * 启用 | 控件Path | 来源 | valueKey | 焦点 | 超时秒 | 别名
+ * 对应 DataPropertyName:Enabled | ControlPath | Source | ValueKey | FocusState | TimeoutSeconds | ContentKey。
+ * 交互清单:
+ * - “添加当前控件”:优先用当前控件树快照生成 XPath(BuildFromTree),没有树时再按 UIA/MSAA/Win32
+ * 单来源构建,三条来源统一产出 XPath 定位信息。
+ * - 点击任意单元格即定位(SelectionChanged 与 CellClick 会同时来,300ms 内去重,见 AutoLocateDedupeMs)。
+ * - 定位与焦点刷新都在后台线程执行,回到 UI 时用 request/revision + 定义身份判断,过期结果直接丢弃。
+ * - 控件Path 可 F2 直接编辑,或双击打开多行 XPath 编辑器(ControlPathEditorForm)。
+ * - 编辑期间(_editingCell / _pathEditorOpen / 单元格编辑中)禁止自动定位。
+ * - PropertyGrid 编辑某定义后必须调用 NotifyDefinitionChanged 以重置该行定位版本。
+ * - 保存前先 CommitEdits(EndEdit)再校验;校验不过不落盘。
+ * - 焦点列由定时器每 3 秒轮询“一行”,避免一次性暴发多次跨进程读取。
+ * 要改什么就改哪里:
+ * - 列定义/顺序:构造函数里的 Columns.Add 与 Column* 常量。
+ * - “添加当前控件”的定位信息构建分支:AddCurrentNode。
+ * - 点击定位与去重:RequestAutoLocate / GridOnSelectionChanged / GridOnCellClick。
+ * - 过期结果丢弃:StartLocate / ApplyLocateResult / IsCurrentLocator。
+ * - 焦点轮询:StateTimerOnTick / RefreshFocusStateAsync / SetRefreshInterval。
+ */
+
namespace pacs_win_uia.UI
{
+ // “已定位到控件”事件参数:定义、命中节点、屏幕矩形、锚定窗口、是否容错、解算步骤与是否显式请求。
public sealed class ControlLocatedEventArgs : EventArgs
{
+ // 便捷重载:默认视为显式定位(isExplicit = true),转调下面的主构造函数。
public ControlLocatedEventArgs(
Models.ControlMonitorDefinition definition,
Models.ControlTreeNode node,
@@ -25,6 +54,7 @@ namespace pacs_win_uia.UI
{
}
+ // 主构造函数:保存各字段。
public ControlLocatedEventArgs(
Models.ControlMonitorDefinition definition,
Models.ControlTreeNode node,
@@ -44,6 +74,7 @@ namespace pacs_win_uia.UI
}
/// True when the control was located through a tolerant path (position may be off).
+ // 是否走了容错路径定位(位置可能不准)。
public bool UsedFallback { get; private set; }
///
@@ -51,40 +82,53 @@ namespace pacs_win_uia.UI
/// is the automatic locate that follows a click in the grid. Only the explicit request toggles
/// the frame off; a click must always show it.
///
+ // 是否操作者主动请求:显式请求(定位按钮/行头/悬浮按钮)同一条目再点一次会关框;网格点击则总是显示框。
public bool Explicit { get; private set; }
/// Top-level window the control lives in; used to hide the frame when it goes away.
+ // 控件所属顶层窗口;该窗口消失时用于隐藏框。
public IntPtr AnchorWindow { get; private set; }
+ // 被定位的监控定义。
public Models.ControlMonitorDefinition Definition { get; private set; }
+ // 定位命中的控件树节点。
public Models.ControlTreeNode Node { get; private set; }
+ // 控件的屏幕矩形(用于画框)。
public Models.NativeRectangleInfo Bounds { get; private set; }
+ // 解算过程步骤(诊断用)。
public IList Steps { get; private set; }
}
+ // “选中了某行定义”事件参数:通知 PropertyGrid 切换编辑对象。
public sealed class DefinitionSelectedEventArgs : EventArgs
{
+ // 构造函数。
public DefinitionSelectedEventArgs(Models.ControlMonitorDefinition definition)
{
Definition = definition;
}
+ // 当前选中的监控定义(可能为 null)。
public Models.ControlMonitorDefinition Definition { get; private set; }
}
+ // “状态栏消息”事件参数:文本 + 可选异常,供主窗体显示。
public sealed class ControlMonitorStatusEventArgs : EventArgs
{
+ // 构造函数。
public ControlMonitorStatusEventArgs(string message, Exception exception)
{
Message = message;
Exception = exception;
}
+ // 状态消息。
public string Message { get; private set; }
+ // 相关异常(无则为 null)。
public Exception Exception { get; private set; }
}
@@ -93,85 +137,134 @@ namespace pacs_win_uia.UI
/// content key — plus what to read from it (valueKey) and where to find it again in each of the
/// three sources.
///
+ // 控件监控定义编辑器(列表)。职责与“要改什么就改哪里”见文件头大块注释。
public sealed class ControlMonitorEditorControl : UserControl
{
/// One click raises SelectionChanged and CellClick; this dedupes the pair (ms).
+ // 点击一次会同时触发 SelectionChanged 与 CellClick,这里去重这一对(毫秒)。
private const int AutoLocateDedupeMs = 300;
+ // 列索引:启用。
private const int ColumnEnabled = 0;
+ // 列索引:控件Path(XPath)。
private const int ColumnPath = 1;
+ // 列索引:来源(Auto/Uia/Msaa/Win32)。
private const int ColumnSource = 2;
+ // 列索引:valueKey(读取的属性名)。
private const int ColumnValueKey = 3;
+ // 列索引:焦点(该控件是否获得焦点,只读)。
private const int ColumnFocus = 4;
+ // 列索引:超时秒。
private const int ColumnTimeout = 5;
+ // 列索引:别名(ContentKey)。
private const int ColumnAlias = 6;
+ // 定义存储(读写配置文件)。
private readonly ControlMonitorStore _store;
+ // 由控件树/节点构建定位信息。
private readonly ControlLocatorBuilder _locatorBuilder;
+ // 定位/窗口查找服务(用于“刷新状态”)。
private readonly ControlLocatorService _locatorService;
+ // 绑定到网格的定义集合。
private readonly BindingList _definitions;
+ // 网格数据源(_definitions → DataGridView)。
private readonly BindingSource _bindingSource;
+ // 主网格。
private readonly DataGridView _grid;
+ // 工具栏:“添加当前控件”。
private readonly Button _addButton;
+ // 工具栏:“删除选中”。
private readonly Button _deleteButton;
+ // 工具栏:“保存”。
private readonly Button _saveButton;
+ // 工具栏:“重载”。
private readonly Button _reloadButton;
+ // 工具栏:“定位到控件”。
private readonly Button _locateButton;
+ // 工具栏:“刷新状态”。
private readonly Button _refreshStatesButton;
+ // 底部消息标签(显示定位信息/校验结果)。
private readonly Label _messageLabel;
+ // valueKey 列(可编辑下拉,候选随来源变化)。
private readonly DataGridViewComboBoxColumn _valueKeyColumn;
+ // “添加当前控件”要快照的当前节点。
private ControlTreeNode _currentNode;
+ // 当前控件树根(存在时“添加当前控件”优先按树生成完整 XPath)。
private ControlTreeNode _currentTreeRoot;
+ // 由 MainForm 每轮设置当前控件树根:存在时“添加当前控件”优先按树快照生成完整 XPath。
public void SetTreeRoot(ControlTreeNode root)
{
_currentTreeRoot = root;
}
+ // 设置焦点轮询定时器周期(毫秒,限幅 100–60000)。
public void SetRefreshInterval(int milliseconds)
{
_stateTimer.Interval = Math.Max(100, Math.Min(60000, milliseconds));
}
+ // “添加当前控件”要用的当前窗口信息。
private NativeWindowInfo _currentWindow;
+ // 是否有未保存修改(“保存”后清除)。
private bool _dirty;
+ // 焦点轮询定时器(默认 3 秒)。
private readonly System.Windows.Forms.Timer _stateTimer;
+ // 工具栏:“自动刷新焦点”复选框。
private readonly CheckBox _autoStateCheck;
+ // 焦点轮询游标:每 tick 只处理一行。
private int _stateCursor;
+ // 是否已有一次焦点刷新在后台进行(避免堆积)。
private bool _stateRefreshInFlight;
///
/// The row/cell the last automatic locate was started for. Clicking another row — or another
/// cell of the same row — is an explicit "show me where this is".
///
+ // 上一次自动定位的行;点击别的行、或同一行的别的单元格都算“显式要求展示”。
private int _lastAutoLocateRow = -1;
+ // 上一次自动定位的列。
private int _lastAutoLocateColumn = -1;
+ // 上一次自动定位的时间戳(TickCount,用于 300ms 去重)。
private int _lastAutoLocateTick;
/// Every locate request gets a number; a slow one that has been superseded is dropped.
+ // 每个定位请求分配一个序号;被后续请求超越的慢结果会被丢弃。
private int _locateRequest;
/// True while the grid is being re-bound: no selection event is a user action then.
+ // 网格重绑期间为 true:此时的选择事件不算用户操作。
private bool _loading;
+ // 单元格是否处于编辑态(CellBeginEdit 置位、CellEndEdit 清除)。
private bool _editingCell;
+ // XPath 多行编辑器是否打开。
private bool _pathEditorOpen;
+ // 当前事件处理期间抑制自动定位(编辑刚结束的那次点击不应再触发定位)。
private bool _suppressAutoLocateUntilIdle;
+ // 每条定义当前的“定位版本”(路径/来源 + 修订号),用于丢弃过期定位结果。
private readonly Dictionary _locatorVersions =
new Dictionary();
+ // 单个定义的定位版本:路径/来源一旦变化,Revision++,使在途结果失效。
private sealed class LocatorVersion
{
+ // 生成该版本时的控件Path。
internal string Path;
+ // 生成该版本时的来源。
internal ControlSourcePreference Source;
+ // 修订号:每次 Path/Source 变化自增。
internal int Revision;
}
+ // 是否处于编辑状态:编辑期间禁止自动定位。
private bool IsEditing
{
get { return _editingCell || _pathEditorOpen || _grid.IsCurrentCellInEditMode; }
}
+ // 默认构造函数:使用默认存储与定位构建器。
public ControlMonitorEditorControl()
: this(new ControlMonitorStore(), new ControlLocatorBuilder())
{
}
+ // 主构造函数:搭建工具栏与网格(含 7 列定义)并绑定事件,最后从存储加载。
public ControlMonitorEditorControl(ControlMonitorStore store, ControlLocatorBuilder locatorBuilder)
{
_store = store ?? throw new ArgumentNullException("store");
@@ -180,6 +273,7 @@ namespace pacs_win_uia.UI
_definitions = new BindingList();
_bindingSource = new BindingSource();
+ // 顶部工具栏:添加/删除/保存/重载/定位/刷新状态/自动刷新焦点。
var toolbar = new FlowLayoutPanel
{
Dock = DockStyle.Top,
@@ -208,6 +302,7 @@ namespace pacs_win_uia.UI
toolbar.Controls.Add(_refreshStatesButton);
toolbar.Controls.Add(_autoStateCheck);
+ // 主网格:单元格选择模式;F2/按键进入编辑(双击控件Path 打开多行 XPath 编辑器)。
_grid = new DataGridView
{
Dock = DockStyle.Fill,
@@ -220,6 +315,7 @@ namespace pacs_win_uia.UI
EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2,
RowHeadersWidth = 28
};
+ // 列0 启用:复选框(勾选即时提交)。
_grid.Columns.Add(new DataGridViewCheckBoxColumn
{
HeaderText = "启用",
@@ -227,6 +323,7 @@ namespace pacs_win_uia.UI
Width = 44,
FlatStyle = FlatStyle.Flat
});
+ // 列1 控件Path:XPath 文本,可编辑(F2/双击)。
_grid.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "控件Path",
@@ -236,6 +333,7 @@ namespace pacs_win_uia.UI
FillWeight = 46,
MinimumWidth = 150
});
+ // 列2 来源:Auto/Uia/Msaa/Win32 下拉。
var sourceColumn = new DataGridViewComboBoxColumn
{
HeaderText = "来源",
@@ -269,6 +367,7 @@ namespace pacs_win_uia.UI
}
_grid.Columns.Add(_valueKeyColumn);
+ // 列4 焦点:只读,显示该控件当前是否获得焦点(由定时器/定位刷新)。
var focusColumn = new DataGridViewTextBoxColumn
{
HeaderText = "焦点(该控件是否获得焦点)",
@@ -277,12 +376,14 @@ namespace pacs_win_uia.UI
Width = 150
};
_grid.Columns.Add(focusColumn);
+ // 列5 超时秒:定位/读取超时。
_grid.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "超时秒",
DataPropertyName = "TimeoutSeconds",
Width = 60
});
+ // 列6 别名:内容键 ContentKey。
_grid.Columns.Add(new DataGridViewTextBoxColumn
{
HeaderText = "别名",
@@ -292,6 +393,7 @@ namespace pacs_win_uia.UI
MinimumWidth = 90
});
+ // 底部消息标签:显示定位信息与校验结果。
_messageLabel = new Label
{
Dock = DockStyle.Bottom,
@@ -304,9 +406,11 @@ namespace pacs_win_uia.UI
Controls.Add(_grid);
Controls.Add(toolbar);
Controls.Add(_messageLabel);
+ // 绑定:BindingList → BindingSource → 网格。
_bindingSource.DataSource = _definitions;
_grid.DataSource = _bindingSource;
+ // 按钮/行头事件接线。
_addButton.Click += delegate { AddCurrentControl(); };
_deleteButton.Click += delegate { DeleteSelected(); };
_saveButton.Click += delegate { Save(); };
@@ -316,6 +420,7 @@ namespace pacs_win_uia.UI
// Clicking the row-header triangle jumps to the control on screen.
_grid.RowHeaderMouseClick += delegate { LocateCurrentDefinition(); };
_grid.SelectionChanged += GridOnSelectionChanged;
+ // 焦点轮询定时器:默认每 3 秒 tick 一次,每次只处理一行。
_stateTimer = new System.Windows.Forms.Timer { Interval = 3000 };
_stateTimer.Tick += StateTimerOnTick;
_stateTimer.Start();
@@ -332,6 +437,7 @@ namespace pacs_win_uia.UI
_grid.RowValidated += delegate { RefreshValidation(); };
_grid.CellBeginEdit += GridOnCellBeginEdit;
_grid.CellValidating += GridOnCellValidating;
+ // 复选框点击立即提交(否则要等离开单元格才写入对象)。
_grid.CurrentCellDirtyStateChanged += delegate
{
// Commit a checkbox click immediately; without this the toggle is not written to the
@@ -343,6 +449,7 @@ namespace pacs_win_uia.UI
};
_grid.SelectionChanged += delegate { ShowSelectedLocator(); };
_grid.CellClick += GridOnCellClick;
+ // 双击:控件Path 打开多行编辑器,其余只读列复制文本。
_grid.CellDoubleClick += GridOnCellDoubleClick;
_grid.CellToolTipTextNeeded += GridOnCellToolTipNeeded;
_grid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
@@ -352,6 +459,7 @@ namespace pacs_win_uia.UI
LoadFromStore();
}
+ // 释放时停止并注销焦点轮询定时器。
protected override void Dispose(bool disposing)
{
if (disposing)
@@ -364,15 +472,19 @@ namespace pacs_win_uia.UI
base.Dispose(disposing);
}
+ // 状态栏消息(定位进度、校验结果、错误)。
public event EventHandler StatusChanged;
/// Raised after a successful locate, so the owner can highlight the control.
+ // 定位成功后触发,让调用方在屏幕上高亮该控件。
public event EventHandler ControlLocated;
/// Raised when the selected row changes, so the property grid can edit that entry.
+ // 选中行变化时触发,让 PropertyGrid 切换到该条目。
public event EventHandler DefinitionSelected;
/// Right-click menu: the read-only columns have to be copyable.
+ // 右键菜单:复制单元格/整行、定位到该控件(只读列也要能复制)。
private ContextMenuStrip BuildGridMenu()
{
var menu = new ContextMenuStrip();
@@ -389,17 +501,20 @@ namespace pacs_win_uia.UI
return menu;
}
+ // 是否有未保存修改。
public bool HasUnsavedChanges
{
get { return _dirty; }
}
+ // 配置文件路径。
public string StoreFilePath
{
get { return _store.FilePath; }
}
/// Remembers the control the "添加当前控件" button should snapshot.
+ // 记住“添加当前控件”要快照的节点与窗口;仅当节点有可用数据源时才启用“添加”按钮。
public void SetCurrentNode(ControlTreeNode node, NativeWindowInfo window)
{
_currentNode = node;
@@ -408,6 +523,7 @@ namespace pacs_win_uia.UI
}
/// Commits any cell being edited; call before hiding the form or saving.
+ // 提交正在编辑的单元格/绑定(隐藏窗体或保存前调用)。
public void CommitEdits()
{
try
@@ -421,6 +537,7 @@ namespace pacs_win_uia.UI
}
}
+ // 从存储重新加载全部定义;重置自动定位记账(加载产生的选择不算用户操作)。
public void LoadFromStore()
{
CommitEdits();
@@ -438,6 +555,7 @@ namespace pacs_win_uia.UI
}
}
+ // 真正加载:读取存储、重建 _definitions 与定位版本,并把焦点列初始化为“未读取”。
private void LoadFromStoreCore()
{
List loaded;
@@ -489,6 +607,7 @@ namespace pacs_win_uia.UI
Report("已加载 " + _definitions.Count + " 条控件监控定义。", null);
}
+ // “添加当前控件”按钮:以 enabled=true 调用 AddCurrentNode,并把结果消息上报状态栏。
private void AddCurrentControl()
{
string message;
@@ -501,6 +620,8 @@ namespace pacs_win_uia.UI
Report(message, null);
}
+ // 把当前节点快照成一条监控条目并追加到列表:优先按当前树快照生成 XPath(BuildFromTree),
+ // 无树时再按 UIA/MSAA/Win32 单来源构建;三条来源统一产出 XPath 定位信息。
///
/// Snapshots the current node as a monitor entry and appends it.
///
@@ -597,6 +718,7 @@ namespace pacs_win_uia.UI
}
/// The page feature suggestion is exactly the window identification that gets saved.
+ // 页面特征建议文本:与保存的窗口识别信息完全一致(进程=…;标题关键词=…;窗口类=…)。
private static string BuildPageFeatures(ControlLocatorBuildResult locator)
{
var builder = new StringBuilder();
@@ -628,6 +750,7 @@ namespace pacs_win_uia.UI
return builder.ToString();
}
+ // “删除选中”:移除当前行并清理其定位版本。
private void DeleteSelected()
{
CommitEdits();
@@ -647,6 +770,7 @@ namespace pacs_win_uia.UI
Report("已删除:" + (removed == null ? "(空行)" : removed.ToString()), null);
}
+ // “保存”:先提交编辑再校验,全部通过才落盘;否则只在状态栏报告首个问题。
private void Save()
{
CommitEdits();
@@ -673,6 +797,7 @@ namespace pacs_win_uia.UI
}
}
+ // “重载”:有未保存修改时先弹确认,再 LoadFromStore。
private void ReloadWithConfirmation()
{
if (_dirty)
@@ -692,12 +817,14 @@ namespace pacs_win_uia.UI
LoadFromStore();
}
+ // 标记有未保存修改。
private void MarkDirty()
{
_dirty = true;
}
/// Offers the keys that make sense for the row's source, while still allowing any text.
+ // 进入编辑:置 _editingCell 并递增定位请求(取消点击定位);对 valueKey 列按来源刷新候选并允许自由输入。
private void GridOnCellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
_editingCell = true;
@@ -741,6 +868,7 @@ namespace pacs_win_uia.UI
}
/// Accepts a hand-typed property name by adding it to the combo's items.
+ // 校验 valueKey 时接受手工输入的属性名:把它加入下拉候选项。
private void GridOnCellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex != ColumnValueKey || _valueKeyColumn == null)
@@ -755,6 +883,7 @@ namespace pacs_win_uia.UI
}
}
+ // 单元格值变化:标记脏;控件Path/来源 变化调用 NotifyDefinitionChanged,其余列只刷新校验。
private void OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (_loading || e.RowIndex < 0) return;
@@ -771,6 +900,7 @@ namespace pacs_win_uia.UI
}
}
+ // 取得/创建某定义的定位版本(首次以当前 Path/Source 初始化)。
private LocatorVersion TrackLocator(ControlMonitorDefinition definition)
{
if (definition == null) return null;
@@ -784,6 +914,7 @@ namespace pacs_win_uia.UI
}
/// Call after PropertyGrid edits too; setters accept unfinished text for repair.
+ // 定义变化时调用(PropertyGrid 编辑后也要调):Path/来源变化则递增修订号、作废在途结果、重置焦点显示。
public void NotifyDefinitionChanged(ControlMonitorDefinition definition)
{
if (definition == null || !_definitions.Contains(definition)) return;
@@ -803,6 +934,7 @@ namespace pacs_win_uia.UI
_grid.Invalidate();
}
+ // 判断结果是否仍“属于当前定义”:定义还在集合里、版本号一致、且 Path/来源未变。
private bool IsCurrentLocator(ControlMonitorDefinition definition,
ControlMonitorDefinition snapshot, int revision)
{
@@ -813,6 +945,7 @@ namespace pacs_win_uia.UI
definition.Source == snapshot.Source;
}
+ // 在当前事件处理期间抑制自动定位,待消息泵空闲(BeginInvoke)后恢复。
private void SuppressAutoLocateForCurrentEvent()
{
_suppressAutoLocateUntilIdle = true;
@@ -823,14 +956,22 @@ namespace pacs_win_uia.UI
}
/// What one locate attempt produced, carried from the worker thread back to the UI.
+ // 一次定位尝试的结果,从工作线程带回 UI 线程。
private sealed class LocateOutcome
{
+ // 是否成功定位。
internal bool Found;
+ // 失败原因(成功为 null)。
internal string Error;
+ // 定位结果(含节点、来源、窗口句柄、是否容错等)。
internal ControlResolution Resolution;
+ // 焦点状态文本。
internal string Focus;
+ // 解算步骤(诊断)。
internal IList Steps;
+ // 耗时(毫秒)。
internal long ElapsedMs;
+ // 是否为显式请求(影响画框开关行为)。
internal bool Explicit;
}
@@ -839,6 +980,7 @@ namespace pacs_win_uia.UI
/// entry, so the owner can expand the control tree to it and draw the frame. Cell edits inside
/// the same row do not re-trigger it.
///
+ // 选中行即请求定位(并广播 DefinitionSelected);加载期间的选择不触发定位。
private void GridOnSelectionChanged(object sender, EventArgs e)
{
RaiseDefinitionSelected();
@@ -853,6 +995,7 @@ namespace pacs_win_uia.UI
///
/// Non-editing clicks locate the row; path clicks are reserved for editing (F2/double-click).
///
+ // 非编辑态点击定位;控件Path 列的点击留给编辑(F2/双击),不在此触发定位。
private void GridOnCellClick(object sender, DataGridViewCellEventArgs e)
{
if (_loading || e.RowIndex < 0)
@@ -867,6 +1010,7 @@ namespace pacs_win_uia.UI
/// One click raises SelectionChanged *and* CellClick; the second one must not start a second
/// resolution, but clicking the same cell again later must locate again.
///
+ // 自动定位入口:编辑中/Path 列/抑制期内不定位;同一行同一列 300ms 内去重,之后再点仍会定位。
private void RequestAutoLocate()
{
if (_loading || IsEditing || _suppressAutoLocateUntilIdle ||
@@ -893,6 +1037,7 @@ namespace pacs_win_uia.UI
}
/// Copies the current cell's text: read-only cells have to be readable somehow.
+ // 复制当前单元格文本(只读列也要能读出来)。
private void CopyCurrentCell()
{
DataGridViewCell cell = _grid.CurrentCell;
@@ -907,6 +1052,7 @@ namespace pacs_win_uia.UI
}
/// Copies the selected row as tab-separated text (usable in Excel).
+ // 把选中行复制为制表符分隔文本(表头 + 内容,可直接粘贴进 Excel)。
private void CopyCurrentRow()
{
int index = _bindingSource.Position;
@@ -939,6 +1085,7 @@ namespace pacs_win_uia.UI
"已复制该行(表头 + 内容):" + Environment.NewLine + builder);
}
+ // 写剪贴板并上报状态;失败只记日志并提示,不抛出。
private void SetClipboard(string text, string report)
{
try
@@ -954,6 +1101,7 @@ namespace pacs_win_uia.UI
}
/// Long values (the control path) are cut off by the column width; show them in full.
+ // 长内容(如控件Path)被列宽截断,悬停时用 ToolTip 显示全文。
private void GridOnCellToolTipNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0)
@@ -969,6 +1117,7 @@ namespace pacs_win_uia.UI
}
}
+ // 双击:控件Path 列打开多行 XPath 编辑器;其它只读列复制文本。
private void GridOnCellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0)
@@ -991,6 +1140,7 @@ namespace pacs_win_uia.UI
CopyCurrentCell();
}
+ // 打开 XPath 多行编辑器:编辑期间置 _pathEditorOpen 禁止自动定位;测试定位用独立快照在工作线程跑。
private void EditControlPath(ControlMonitorDefinition definition)
{
if (definition == null || _pathEditorOpen) return;
@@ -1036,6 +1186,7 @@ namespace pacs_win_uia.UI
/// seconds on a busy PACS client, so it runs on a worker thread; the result is applied on the
/// UI thread and dropped if another row has been selected meanwhile.
///
+ // “定位到控件”/行头/右键菜单入口:先提交编辑,再以显式请求启动后台定位。
public void LocateCurrentDefinition()
{
CommitEdits();
@@ -1046,6 +1197,8 @@ namespace pacs_win_uia.UI
/// True for 定位按钮 / 行头 / 悬浮按钮: only those toggle the frame off when the same entry is
/// asked for twice. A click in the grid always shows the frame.
///
+ // 启动一次后台定位:分配请求号、校验路径、复制快照;工作线程里查找窗口→Resolve→读焦点,
+ // 再回 UI 线程交给 ApplyLocateResult(凭请求号 + 版本丢弃过期结果)。
private void StartLocate(ControlMonitorDefinition definition, bool isExplicit, string trigger)
{
if (definition == null)
@@ -1152,6 +1305,7 @@ namespace pacs_win_uia.UI
}
/// A copy of the locator fields: the operator may edit or delete the row while the read runs.
+ // 复制定位相关字段的快照:读取运行期间操作者可能编辑或删除该行。
private static ControlMonitorDefinition Snapshot(ControlMonitorDefinition definition)
{
var snapshot = new ControlMonitorDefinition
@@ -1198,6 +1352,7 @@ namespace pacs_win_uia.UI
return snapshot;
}
+ // 在 UI 线程应用定位结果:请求号/选中项/版本任一对不上(含已编辑、删除、重载)就丢弃。
private void ApplyLocateResult(int request, ControlMonitorDefinition definition,
ControlMonitorDefinition snapshot, int revision, LocateOutcome outcome)
{
@@ -1241,6 +1396,7 @@ namespace pacs_win_uia.UI
/// Locates every enabled entry and refreshes its focus state. Each entry is timed on its own,
/// so one missing control cannot delay the others.
///
+ // 定位所有“已启用”条目并刷新焦点状态;每条独立计时,单条失败不影响其他。注意:在 UI 线程同步执行。
public void RefreshAllStates()
{
CommitEdits();
@@ -1296,6 +1452,7 @@ namespace pacs_win_uia.UI
Report(string.Format("状态刷新完成:成功 {0} 条,失败 {1} 条(每条独立计时)。", located, failed), null);
}
+ // 取节点屏幕矩形:优先 UIA BoundingRectangle,其次 MSAA Location,最后窗口边界。
private static NativeRectangleInfo BoundsOf(ControlTreeNode node)
{
if (node == null)
@@ -1320,6 +1477,7 @@ namespace pacs_win_uia.UI
/// One row per tick, on a background thread: the 焦点 column is "does this control have focus
/// right now", and keeping it current costs one bounded resolution per tick instead of a burst.
///
+ // 焦点轮询 tick:从 _stateCursor 起找一条已启用定义,异步刷新其焦点状态后立即返回(每 tick 只一行)。
private void StateTimerOnTick(object sender, EventArgs e)
{
if (IsDisposed || IsEditing || _stateRefreshInFlight || !_autoStateCheck.Checked || _definitions.Count == 0)
@@ -1342,6 +1500,7 @@ namespace pacs_win_uia.UI
}
}
+ // 后台定位单条定义并读取焦点;回 UI 后按 index/定义身份/revision 判断,过期则丢弃。
private void RefreshFocusStateAsync(int index, ControlMonitorDefinition definition)
{
_stateRefreshInFlight = true;
@@ -1422,23 +1581,27 @@ namespace pacs_win_uia.UI
}
/// The monitor row currently selected, for actions that need a target.
+ // 供需要目标的操作取当前选中条目(先提交编辑)。
public ControlMonitorDefinition SelectedDefinitionForActions()
{
CommitEdits();
return SelectedDefinition();
}
+ // 当前选中位置的条目(越界返回 null)。
private ControlMonitorDefinition SelectedDefinition()
{
int index = _bindingSource.Position;
return index >= 0 && index < _definitions.Count ? _definitions[index] : null;
}
+ // 设置某行错误提示(供定位失败等调用)。
private void MarkRowError(ControlMonitorDefinition definition, string error)
{
SetRowError(definition, error);
}
+ // 把错误文本写到对应网格行的 ErrorText。
private void SetRowError(ControlMonitorDefinition definition, string error)
{
int index = _definitions.IndexOf(definition);
@@ -1448,6 +1611,7 @@ namespace pacs_win_uia.UI
}
}
+ // 触发 DefinitionSelected 事件,广播当前选中定义。
private void RaiseDefinitionSelected()
{
EventHandler handler = DefinitionSelected;
@@ -1457,6 +1621,7 @@ namespace pacs_win_uia.UI
}
}
+ // 在底部消息标签显示选中行的定位摘要(来源/进程/窗口类/UIA/MSAA/Win32/RuntimeId)。
private void ShowSelectedLocator()
{
int index = _bindingSource.Position;
@@ -1503,6 +1668,7 @@ namespace pacs_win_uia.UI
/// Cross-row rules cannot be expressed through IDataErrorInfo, so they are applied here
/// after the edit is committed; the grid itself only reports per-field problems.
///
+ // 编辑提交后统一做跨行校验(IDataErrorInfo 表达不了),把错误写到行与底部消息标签。
private void RefreshValidation()
{
IList errors = ControlMonitorStore.TryValidate(GetDefinitions());
@@ -1557,6 +1723,7 @@ namespace pacs_win_uia.UI
_messageLabel.Text = builder.ToString();
}
+ // 网格数据错误:一律取消(Cancel=true)并记日志,绝不让被拒的值升级为未处理异常。
private void GridOnDataError(object sender, DataGridViewDataErrorEventArgs e)
{
// Never let a rejected value escalate into an unhandled exception.
@@ -1564,11 +1731,13 @@ namespace pacs_win_uia.UI
AppLog.Warn("控件监控列表单元格错误:" + e.Exception);
}
+ // 返回定义集合的浅拷贝(供校验/保存)。
private IList GetDefinitions()
{
return new List(_definitions);
}
+ // 依来源推导默认别名:MSAA Name / Win32 标题 / UIA AutomationId(无则 Name),并做去重编号。
private string SuggestContentKey(ControlTreeNode node)
{
string source = null;
@@ -1606,6 +1775,7 @@ namespace pacs_win_uia.UI
return key;
}
+ // 别名是否已被占用(用于生成唯一 ContentKey)。
private bool ContainsKey(string key)
{
foreach (ControlMonitorDefinition definition in _definitions)
@@ -1623,6 +1793,7 @@ namespace pacs_win_uia.UI
/// The key has to survive the store's ASCII identifier pattern, so anything else
/// (including Chinese names) is dropped and a numbered fallback is used instead.
///
+ // 把建议文本清洗为符合存储 ASCII 标识符规则的键;不合法字符折叠为下划线,过长截断。
private static string SanitizeKey(string value)
{
if (string.IsNullOrEmpty(value))
@@ -1667,6 +1838,7 @@ namespace pacs_win_uia.UI
return sanitized;
}
+ // 触发 StatusChanged 上报状态消息。
private void Report(string message, Exception exception)
{
EventHandler handler = StatusChanged;
diff --git a/src/pacs_win_uia/UI/ControlPathEditorForm.cs b/src/pacs_win_uia/UI/ControlPathEditorForm.cs
index e10cb0b..7b34e5f 100644
--- a/src/pacs_win_uia/UI/ControlPathEditorForm.cs
+++ b/src/pacs_win_uia/UI/ControlPathEditorForm.cs
@@ -5,11 +5,27 @@ using System.Threading.Tasks;
using System.Windows.Forms;
using pacs_win_uia.Models;
+/*
+ * ControlPathEditorForm —— 控件 XPath 多行编辑器。
+ * 职责:编辑单条监控条目的 XPath;可选地在后台线程上对“快照”测试定位,避免阻塞 UI。
+ * 被谁调用:ControlMonitorEditorControl.EditControlPath —— 双击“控件Path”单元格时打开。
+ * 交互清单:
+ * - 顶部 XPath 1.0 帮助文本(只读)。
+ * - 中部多行文本框(AcceptsReturn:回车是换行,不提交对话框)。
+ * - 底部状态行 + 按钮:保存(校验通过才置 OK 并关闭)、取消、测试定位(后台唯一匹配)。
+ * - 文本变化:递增 _textRevision 并即时校验。
+ * 要改什么就改哪里:
+ * - 帮助文本:XPathHelp 常量。
+ * - 校验规则:ControlMonitorRules.ValidateControlPath(仅接受 XPath,拒绝旧格式,须唯一匹配)。
+ * - 测试定位如何后台执行:TestLocateOnClick。
+ */
+
namespace pacs_win_uia.UI
{
/// Edits plain XPath text; optional resolution runs off the UI thread on a snapshot.
public sealed class ControlPathEditorForm : Form
{
+ // XPath 帮助文本:工具内所有“控件Path”统一用 XPath 1.0;勿加 [Uia] 等前缀或旧的 > 分隔路径。
internal const string XPathHelp =
"XPath 1.0:/ 从所选窗口根开始,/ 子级,// 后代,* 任意控件,[1] 同级序号(从 1 开始)。\r\n"
+ "示例:/Window//Button[@Name='确定'] 或 //*[@AutomationId='saveButton']\r\n"
@@ -17,14 +33,21 @@ namespace pacs_win_uia.UI
+ "UIA / MSAA / Win32 均使用 XPath;不要加 [Uia] 等前缀或旧的 > 分隔路径。\r\n"
+ "定位必须唯一匹配控件元素;0 个、多个匹配或属性/文本结果均报错。";
+ // 路径输入框。
private readonly TextBox _path;
+ // 底部状态/校验提示行。
private readonly Label _status;
+ // “测试定位”按钮;无回调时保持禁用。
private readonly Button _testButton;
+ // 后台测试回调:返回 null 表示唯一匹配,否则返回错误文本;为 null 表示不支持测试。
private readonly Func _testLocate;
+ // 文本修订号:用于丢弃过期的后台测试结果。
private int _textRevision;
+ // 是否正在后台测试,防止重复触发。
private bool _testing;
/// Optional worker callback; returns null for one match, or an error.
+ // 构造函数:initialPath 为初始路径;testLocate 为可选的后台测试回调(null 则禁用“测试定位”)。
public ControlPathEditorForm(string initialPath, Func testLocate)
{
Text = "编辑控件 XPath";
@@ -70,6 +93,7 @@ namespace pacs_win_uia.UI
};
var cancel = new Button { Text = "取消", AutoSize = true, DialogResult = DialogResult.Cancel };
var save = new Button { Text = "保存", AutoSize = true };
+ // 保存:校验通过才返回 OK 并关闭;这里只更新当前行,写入配置文件仍需点列表的“保存”。
save.Click += delegate
{
if (!ValidatePath()) return;
@@ -87,6 +111,7 @@ namespace pacs_win_uia.UI
Controls.Add(buttons);
CancelButton = cancel;
// Enter remains a newline in the multiline editor; save is an explicit button action.
+ // 多行编辑器中回车是换行;保存只走显式按钮。文本变化时递增修订号并即时校验。
_path.TextChanged += delegate
{
_textRevision++;
@@ -95,8 +120,10 @@ namespace pacs_win_uia.UI
ValidatePath();
}
+ // 编辑后的路径文本;保存时由调用方读取。
public string PathText { get { return _path.Text; } }
+ // 校验当前文本并把结果写到状态行;返回是否合法。
private bool ValidatePath()
{
string error = ControlMonitorRules.ValidateControlPath(_path.Text);
@@ -104,12 +131,14 @@ namespace pacs_win_uia.UI
return error == null;
}
+ // 更新状态行文本与颜色(错误为红色,正常为深灰)。
private void ShowStatus(string text, bool error)
{
_status.ForeColor = error ? Color.Firebrick : Color.DarkSlateGray;
_status.Text = text;
}
+ // 在后台线程对快照测试唯一匹配;结果按 _textRevision 去重,过期(编辑过文本)则丢弃。
private async void TestLocateOnClick(object sender, EventArgs e)
{
if (_testing || _testLocate == null || !ValidatePath()) return;
diff --git a/src/pacs_win_uia/UI/ControlTreeReconciler.cs b/src/pacs_win_uia/UI/ControlTreeReconciler.cs
index 96ef5e7..684a474 100644
--- a/src/pacs_win_uia/UI/ControlTreeReconciler.cs
+++ b/src/pacs_win_uia/UI/ControlTreeReconciler.cs
@@ -5,27 +5,54 @@ using System.Runtime.InteropServices;
using System.Windows.Forms;
using pacs_win_uia.Models;
+/*
+ * ControlTreeReconciler —— 控件树“就地复用”节点,避免每 300ms 清空重建。
+ * 为什么不能每 300ms 清空重建:整树 Clear()+重建会可见闪烁、丢失当前选择/展开状态与滚动位置,
+ * 还会打断正在进行的编辑。这里改为复用旧 TreeNode,只更新变化的文本/字体/颜色,结构变化时尽量保留状态。
+ * 节点身份规则(Identity,绝不使用会变的显示文本/Name):
+ * - UIA:进程号 + RuntimeId; - Win32:进程号 + HWND; - MSAA:PathKey。
+ * 身份只在同一“保留的父节点”内、按出现顺序匹配(Fallback 兜底);文本与 Tag 分开更新:
+ * Tag 永远指向最新快照模型,Text/字体/颜色只在变化时更新。
+ * 被谁调用:MainForm.ReconcileTreeView —— 每轮快照构建 ControlTreeReconciler.Item 树后调用 Apply。
+ * 要改什么就改哪里:
+ * - 身份判定:Identity / Fallback。
+ * - 复用与结构重建:Reserve / Bind / Place。
+ * - 选择/展开/横向滚动恢复:Apply 末尾。
+ */
+
namespace pacs_win_uia.UI
{
/// Reuses native tree items across snapshots. Identity never depends on display text/path.
internal sealed class ControlTreeReconciler : IDisposable
{
+ // 期望的“视图”节点:由 MainForm 依据最新快照构建,Reconciler 负责把它套用到旧 TreeNode 上。
internal sealed class Item
{
+ // 该节点对应的最新模型快照(最终写入 TreeNode.Tag)。
internal ControlTreeNode Model;
+ // 期望显示文本。
internal string Text;
+ // 是否是搜索命中项(命中项用加粗字体)。
internal bool Match;
+ // 期望前景色。
internal Color ForeColor;
+ // 期望的子节点(按顺序)。
internal readonly List- Children = new List
- ();
+ // 复用后绑定到的真实 TreeNode(由 Reserve/Bind 填充)。
internal TreeNode Node;
}
+ // 目标 TreeView。
private readonly TreeView _tree;
+ // 命中项的加粗字体(缓存,随基础字体变化重建)。
private Font _matchFont;
+ // 重建 _matchFont 时记录的基础字体。
private Font _baseFont;
+ // 构造函数:绑定需要复用节点的 TreeView。
internal ControlTreeReconciler(TreeView tree) { _tree = tree; }
+ // 强身份可跨父节点移动;用进程号限定避免跨进程误复用。返回 null 表示该节点没有可用强身份。
// Strong identities can move between parents. Process scoping prevents cross-process reuse.
internal static string Identity(ControlTreeNode node)
{
@@ -45,8 +72,11 @@ namespace pacs_win_uia.UI
return null;
}
+ // 把字符串编码为“长度:内容”,使拼接后的 Fallback 键不会因内容里的分隔符而产生歧义。
private static string Part(string text) { return (text ?? string.Empty).Length + ":" + text; }
+ // 仅在同一个保留父节点内、按出现顺序匹配的兜底身份;缺少提供方 ID 时
+ // 无法可靠跟踪任意重排的不可区分同级节点。
// Only matched within the same retained parent, in occurrence order. Without provider IDs,
// indistinguishable siblings cannot reliably be tracked through arbitrary reordering.
private static string Fallback(ControlTreeNode node)
@@ -63,6 +93,7 @@ namespace pacs_win_uia.UI
return node.Source.ToString();
}
+ // 用期望的 Item 树就地更新 TreeView:强身份优先复用旧节点,再兜底绑定,最后清理多余节点并恢复选择/展开/滚动。
internal void Apply(Item root, IList matches)
{
var oldNodes = new List();
@@ -142,6 +173,7 @@ namespace pacs_win_uia.UI
}
}
+ // 统计期望树中每个强身份出现的次数;只有恰好出现一次的身份才可安全复用(避免张冠李戴)。
private static void CountIdentities(Item item, Dictionary counts)
{
if (item == null) return;
@@ -150,6 +182,7 @@ namespace pacs_win_uia.UI
foreach (Item child in item.Children) CountIdentities(child, counts);
}
+ // 第一遍:为身份唯一、且能在旧节点中找到的项占位,避免后续兜底绑定“抢走”别处需要的节点。
private static void Reserve(Item item, Dictionary old, Dictionary counts, HashSet used)
{
if (item == null) return;
@@ -164,6 +197,7 @@ namespace pacs_win_uia.UI
foreach (Item child in item.Children) Reserve(child, old, counts, used);
}
+ // 第二遍:Reserve 未占到位的项,在同级未使用节点里按身份/兜底键寻找可复用节点,找不到则新建。
private static void Bind(Item item, TreeNodeCollection siblings, HashSet used)
{
if (item.Node == null)
@@ -188,6 +222,7 @@ namespace pacs_win_uia.UI
foreach (Item child in item.Children) Bind(child, item.Node.Nodes, used);
}
+ // 递归把节点放到正确位置(需要时先移除再插入),只更新有变化的文本/字体/颜色;命中项加入 matches。
private void Place(Item item, TreeNodeCollection siblings, int index, IList matches, Action beginStructure, ref bool changed)
{
TreeNode node = item.Node;
@@ -207,11 +242,13 @@ namespace pacs_win_uia.UI
if (item.Match) matches.Add(node);
}
+ // 递归收集整棵树的所有节点(用于身份索引与遍历对比)。
private static void Collect(TreeNodeCollection nodes, List result)
{
foreach (TreeNode node in nodes) { result.Add(node); Collect(node.Nodes, result); }
}
+ // 返回从 node 到根的祖先链(用于结构重建后恢复选择与顶节点)。
private static List Ancestors(TreeNode node)
{
var result = new List();
@@ -219,21 +256,26 @@ namespace pacs_win_uia.UI
return result;
}
+ // 返回第一个仍挂在当前树上的节点(结构重建后旧引用可能已脱离)。
private TreeNode FirstAttached(List nodes)
{
foreach (TreeNode node in nodes) if (node.TreeView == _tree) return node;
return null;
}
+ // 释放缓存的加粗字体。
public void Dispose()
{
if (_matchFont != null) { _matchFont.Dispose(); _matchFont = null; }
}
+ // 读取滚动条位置(bar=0 为水平滚动条)。
[DllImport("user32.dll")]
private static extern int GetScrollPos(IntPtr window, int bar);
+ // 设置滚动条位置。
[DllImport("user32.dll")]
private static extern int SetScrollPos(IntPtr window, int bar, int position, bool redraw);
+ // 发送窗口消息(此处用于 WM_HSCROLL 同步滚动条)。
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr window, int message, IntPtr wParam, IntPtr lParam);
}
diff --git a/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs b/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs
index 88888b5..45b167f 100644
--- a/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs
+++ b/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs
@@ -3,25 +3,51 @@ using System.Drawing;
using System.Windows.Forms;
using pacs_win_uia.Models;
+/*
+ * ControlTreeSearchPanel —— 控件树搜索栏(内含 TreeSearchCriteria 搜索条件)。
+ * 职责:只负责收集搜索条件(默认一个“搜索”框,点“更多…”展开详细字段),自己不遍历树;
+ * 真正的遍历与过滤在拥有它的 MainForm(ReconcileTreeView)里做。
+ * 被谁调用:MainForm 在控件树上方创建(new ControlTreeSearchPanel { Dock = Top })。
+ * 搜索条件字段(AND 关系,所有已填字段都要匹配):
+ * Any(任一标识字段包含)、Name(名称)、Path(路径,按 path 搜索时走 XPath 判定)、
+ * AutomationId、ClassName(类名)、ControlType(类型)、OnlyFocused(仅焦点元素)。
+ * 交互清单:
+ * - 顶行:搜索框、仅显示匹配、▲▼、匹配计数、“更多…/收起”(窄宽度会自动换行)。
+ * - 更多面板:5 列 × 3 行表格(标题 / 输入框 / 按钮行),字段为 名称、路径、AutomationId、类名、类型。
+ * - 应用 / 清除 / 仅焦点元素;详细输入框不逐键过滤,靠“应用”或回车提交。
+ * 要改什么就改哪里:
+ * - 顶行控件与尺寸:构造函数。
+ * - 行高随宽度自适应:UpdateHeights / MeasureWrappedHeight。
+ * - 匹配规则:TreeSearchCriteria.Matches / MatchesAny / MatchesField。
+ */
+
namespace pacs_win_uia.UI
{
/// What the tree search is looking for. All filled fields must match (AND).
public sealed class TreeSearchCriteria
{
+ // 简易搜索框:任一标识字段(含 path)含该子串即命中。
public string Any { get; set; }
+ // 名称:UIA Name / MSAA Name / 窗口标题。
public string Name { get; set; }
+ // 路径:填合法 XPath 时由 MainForm 走 XPath 判定(ControlPath.Select),否则按祖先路径文本包含匹配。
public string Path { get; set; }
+ // UIA AutomationId。
public string AutomationId { get; set; }
+ // 类名:UIA ClassName / 窗口类名。
public string ClassName { get; set; }
+ // 类型:UIA ControlType / MSAA RoleText。
public string ControlType { get; set; }
+ // 仅匹配当前拥有键盘焦点的元素(焦点状态来自树快照)。
public bool OnlyFocused { get; set; }
+ // 所有字段均为空(且不限焦点)时为 true,表示本次搜索无有效条件。
public bool IsEmpty
{
get
@@ -33,6 +59,7 @@ namespace pacs_win_uia.UI
}
}
+ // 判断节点是否满足全部已填条件(AND);path 为祖先路径文本,focused 来自树快照。
/// Ancestor path of the node ("Pane:x > List:y"), used by the path field.
/// Focus state from the tree snapshot.
public bool Matches(ControlTreeNode node, string path, bool focused)
@@ -67,6 +94,7 @@ namespace pacs_win_uia.UI
}
/// The simple box matches any of the identifying fields.
+ // 简易搜索框:任一标识字段(含 path)忽略大小写包含 filter 即命中;filter 为空视为命中。
private static bool MatchesAny(string filter, ControlTreeNode node, string path)
{
if (string.IsNullOrWhiteSpace(filter))
@@ -85,6 +113,7 @@ namespace pacs_win_uia.UI
|| Contains(path, filter);
}
+ // 详细字段匹配:filter 为空视为命中;否则三个候选值中任一包含 filter(忽略大小写)即命中。
private static bool MatchesField(string filter, string first, string second, string third)
{
if (string.IsNullOrWhiteSpace(filter))
@@ -95,6 +124,7 @@ namespace pacs_win_uia.UI
return Contains(first, filter) || Contains(second, filter) || Contains(third, filter);
}
+ // 忽略大小写的包含判断;value 为空返回 false。
private static bool Contains(string value, string filter)
{
return !string.IsNullOrEmpty(value) &&
@@ -108,30 +138,54 @@ namespace pacs_win_uia.UI
///
public sealed class ControlTreeSearchPanel : UserControl
{
+ // 顶行:简易搜索框。
private readonly TextBox _anyBox;
+ // 顶行:“仅显示匹配”复选框。
private readonly CheckBox _onlyMatches;
+ // 顶行:上一条匹配(▲)。
private readonly Button _previous;
+ // 顶行:下一条匹配(▼)。
private readonly Button _next;
+ // 顶行:“更多…/收起”切换按钮。
private readonly Button _more;
+ // 顶行:匹配计数标签。
private readonly Label _countLabel;
+ // “更多…”详细条件面板。
private readonly Panel _advanced;
+ // 顶行流式布局容器(窄宽度会自动换行)。
private readonly FlowLayoutPanel _bar;
+ // 详细条件表格(5 列 × 3 行)。
private readonly TableLayoutPanel _grid;
+ // 详细条件:名称输入框。
private readonly TextBox _nameBox;
+ // 详细条件:路径输入框。
private readonly TextBox _pathBox;
+ // 详细条件:AutomationId 输入框。
private readonly TextBox _automationIdBox;
+ // 详细条件:类名输入框。
private readonly TextBox _classBox;
+ // 详细条件:类型输入框。
private readonly TextBox _typeBox;
+ // 详细条件:仅焦点元素复选框。
private readonly CheckBox _onlyFocused;
+ // 详细条件:“应用”按钮。
private readonly Button _apply;
+ // 详细条件:“清除”按钮。
private readonly Button _clear;
+ // “更多”面板当前是否展开。
private bool _advancedVisible;
+ // 上次测量行高时的宽度;用于决定是否需要重算。
private int _measuredWidth = -1;
+ // 当前顶行高度(换行时大于 28)。
private int _barHeight = 28;
+ // 当前“更多”面板高度。
private int _advancedHeight = 58;
+ // 上次记录诊断日志时的宽度(避免重复记录)。
private int _loggedWidth = -1;
+ // 上次记录诊断日志时的展开状态。
private bool _loggedAdvanced;
+ // 构造函数:搭建顶行与“更多”面板,并按当前宽度测量高度。
public ControlTreeSearchPanel()
{
Height = 28;
@@ -218,6 +272,7 @@ namespace pacs_win_uia.UI
UpdateHeights();
}
+ // 宽度变化时重算行高,避免换行后内容被裁掉。
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
@@ -231,6 +286,7 @@ namespace pacs_win_uia.UI
/// Sizes the two rows (and the whole panel) to the content at the *current* width. Both rows
/// wrap, so the required height depends on how wide this panel ended up being.
///
+ // 按当前宽度测量两行(及整面板)所需高度:两行都会换行,所需高度取决于面板实际宽度。
private void UpdateHeights()
{
_measuredWidth = Width;
@@ -267,6 +323,7 @@ namespace pacs_win_uia.UI
}
}
+ // 用 GetPreferredSize 估算 panel 在给定宽度下换行后的高度(不小于 minimum)。
private static int MeasureWrappedHeight(Control panel, int width, int minimum)
{
if (panel == null)
@@ -279,11 +336,14 @@ namespace pacs_win_uia.UI
}
/// Fires when the criteria change; the owner re-applies filtering.
+ // 条件变化时触发,由 MainForm 重新应用过滤。
public event EventHandler SearchChanged;
/// +1 = next match, -1 = previous match.
+ // 请求跳到下一条(+1)/上一条(-1)匹配。
public event EventHandler NavigateRequested;
+ // 当前搜索条件(从各输入框读取)。
public TreeSearchCriteria Criteria
{
get
@@ -301,30 +361,35 @@ namespace pacs_win_uia.UI
}
}
+ // “仅显示匹配”是否勾选;未勾选时匹配项高亮但全部显示。
public bool OnlyMatches
{
get { return _onlyMatches.Checked; }
}
/// Ctrl+F support: put the caret in the search box.
+ // Ctrl+F:把光标放到搜索框并全选。
public void FocusSearchBox()
{
_anyBox.Focus();
_anyBox.SelectAll();
}
+ // 更新匹配计数标签(0 项显示红色)。
public void SetMatchCount(int count)
{
_countLabel.Text = count == 0 ? "匹配 0 项" : "匹配 " + count + " 项";
_countLabel.ForeColor = count == 0 ? Color.Firebrick : Color.DarkSlateGray;
}
+ // 启用/禁用 ▲▼ 导航按钮。
public void SetNavigationEnabled(bool enabled)
{
_previous.Enabled = enabled;
_next.Enabled = enabled;
}
+ // 在表格某列加“标题 + 输入框”一对控件并返回输入框;这些框不逐键过滤,靠“应用/回车”提交。
private TextBox AddField(TableLayoutPanel parent, string label, int column)
{
parent.Controls.Add(new Label
@@ -340,6 +405,7 @@ namespace pacs_win_uia.UI
return box;
}
+ // 展开/收起“更多”面板,重算高度并刷新按钮文案。
private void ToggleAdvanced()
{
_advancedVisible = !_advancedVisible;
@@ -349,6 +415,7 @@ namespace pacs_win_uia.UI
RaiseSearchChanged();
}
+ // 清空所有搜索条件并触发一次搜索。
private void ClearAll()
{
_anyBox.Text = string.Empty;
@@ -362,6 +429,7 @@ namespace pacs_win_uia.UI
RaiseSearchChanged();
}
+ // 触发 SearchChanged 事件。
private void RaiseSearchChanged()
{
EventHandler handler = SearchChanged;
@@ -371,6 +439,7 @@ namespace pacs_win_uia.UI
}
}
+ // 触发 NavigateRequested 事件,携带方向(+1 / -1)。
private void RaiseNavigate(int direction)
{
EventHandler handler = NavigateRequested;
diff --git a/src/pacs_win_uia/UI/FloatingToolbarForm.cs b/src/pacs_win_uia/UI/FloatingToolbarForm.cs
index 599e4e7..f128ceb 100644
--- a/src/pacs_win_uia/UI/FloatingToolbarForm.cs
+++ b/src/pacs_win_uia/UI/FloatingToolbarForm.cs
@@ -9,8 +9,37 @@ using pacs_win_uia.Diagnostics;
using pacs_win_uia.Interop;
using pacs_win_uia.Models;
+// ============================================================================
+// FloatingToolbarForm —— 单条“悬浮条”窗体(自绘 layered window)
+//
+// 职责:
+// 一条始终置顶、永不抢焦点的小操作条,贴在 PACS 窗口旁。背景与一排按钮全部自绘。
+// 显示/隐藏/定位由 FloatingBarManager 按配置条件驱动;本类只负责“长什么样 + 怎么响应鼠标”。
+//
+// 被谁调用:
+// 由 FloatingBarManager 创建并放进 BarRuntime.Form;按钮点击通过 ActionInvoked 事件回传,
+// manager 再匹配按钮并触发真正的动作。
+//
+// 节拍与线程:纯 UI 线程,无定时器;每次视觉变化(悬停/按下/尺寸变化)都会 Render 一次。
+//
+// 不抢焦点/点击穿透:
+// · CreateParams 设 WS_EX_TOOLWINDOW|WS_EX_NOACTIVATE|WS_EX_LAYERED;ShowWithoutActivation=true。
+// · WM_NCHITTEST:圆角外的空白返回 HTTRANSPARENT 让其穿透,命中处返回 HTCLIENT。
+//
+// 自绘要点:
+// · 背景与按钮分别透明(WinForms 子控件做不到),靠 UpdateLayeredWindow + ARGB 位图实现圆角与逐像素透明。
+// · 逐像素透明不可用时退化为“整条不透明度”(_layeredFailed 标记)。
+// · hBitmap 用完必须 DeleteObject,DC 必须释放,否则句柄泄漏。
+// · WM_NCHITTEST 拿到的鼠标坐标是屏幕坐标,必须先 PointToClient 转客户区再判定。
+// · 按钮派发用 FloatingButtonDefinition 对象引用而不是显示名(避免同名按钮误触)。
+//
+// “要改什么就改哪里”:
+// · 布局尺寸 → BuildLayout / MeasureBar;外观 → DrawBar / RoundedRect
+// · 透明与位图提交 → Render / ApplyBitmap;命中与拖动 → WndProc / HitTest / OnMouse* 系列
+// ============================================================================
namespace pacs_win_uia.UI
{
+ /// 悬浮条按钮点击事件参数:按钮定义 + 显示文案。
public sealed class FloatingActionEventArgs : EventArgs
{
public FloatingActionEventArgs(string action)
@@ -25,9 +54,11 @@ namespace pacs_win_uia.UI
}
/// Stable configured button instance, avoiding duplicate-label dispatch.
+ /// 稳定的按钮定义对象引用,用于按引用派发、避免同名按钮误触。
public FloatingButtonDefinition Button { get; private set; }
/// Display label of the clicked button.
+ /// 被点击按钮的显示文案。
public string Action { get; private set; }
}
@@ -41,9 +72,11 @@ namespace pacs_win_uia.UI
/// and rendered through UpdateLayeredWindow, which is also what gives the rounded corners. Showing,
/// hiding and positioning are driven by FloatingBarManager from the configured condition.
///
+ /// 一条悬浮条窗体:自绘、置顶、不抢焦点、可点击穿透;外观与响应都在本类。
public sealed class FloatingToolbarForm : Form
{
/// Ready-made actions the settings dialog offers.
+ /// 设置页可选的现成动作清单。
public static readonly IList KnownActions = new List
{
FloatingActionKind.ReadList,
@@ -56,31 +89,52 @@ namespace pacs_win_uia.UI
FloatingActionKind.RunCommand
};
+ /// 条内四周留白(像素)。
private const int EdgePadding = 6;
+ /// 按钮左右内边距。
private const int ButtonPaddingX = 10;
+ /// 按钮上下内边距。
private const int ButtonPaddingY = 5;
+ /// 按钮之间的水平间距。
private const int ButtonGap = 4;
+ /// 不透明时的 alpha 值(255)。
private const byte SolidAlpha = 255;
+ /// 本条的配置定义(拖动结束后会被回写相对偏移)。
private readonly FloatingBarDefinition _bar;
+ /// 当前布局出的按钮(含命中矩形与文案)。
private readonly List _buttons = new List();
+ /// 悬停提示气泡(复用实例,避免频繁创建)。
private readonly ToolTip _tooltip = new ToolTip();
+ /// 按下拖动时,鼠标相对窗体左上角的偏移。
private Point _dragOffset;
+ /// 是否正在拖动(manager 据此在拖动期间暂停跟随)。
private bool _dragging;
+ /// 当前悬停按钮索引(-1 表示无)。
private int _hoverIndex = -1;
+ /// 当前按下按钮索引(-1 表示无)。
private int _pressedIndex = -1;
+ /// 是否成功使用逐像素透明(UpdateLayeredWindow)。
private bool _layered;
+ /// 逐像素透明失败,已退化为整条不透明度。
private bool _layeredFailed;
+ /// 当前已显示的 tooltip 文本,避免重复 Show。
private string _shownTooltip;
+ /// 一个按钮的布局与显示数据。
private sealed class ButtonLayout
{
+ /// 按钮定义(派发时按此引用匹配,而非显示名)。
internal FloatingButtonDefinition Definition;
+ /// 按钮在窗体客户区内的命中矩形。
internal Rectangle Bounds;
+ /// 显示文案(未填时由动作类型生成)。
internal string Label;
+ /// 悬停提示文本(含快捷键与命令行)。
internal string Tooltip;
}
+ /// 用配置构建窗体:无边框、不进任务栏、置顶、手动定位,并完成首次布局与尺寸测量。
public FloatingToolbarForm(FloatingBarDefinition bar)
{
_bar = bar ?? new FloatingBarDefinition();
@@ -94,18 +148,21 @@ namespace pacs_win_uia.UI
ClientSize = MeasureBar();
}
+ /// 按钮被点击时触发(携带按钮定义与显示文案)。
public event EventHandler ActionInvoked;
///
/// True when the bar is rendered with per-pixel alpha (background and buttons can differ).
/// False means the window fell back to a single window opacity.
///
+ /// 是否使用逐像素透明绘制(背景与按钮可分别设透明度);false 表示退化为整条不透明度。
public bool UsesPerPixelAlpha
{
get { return _layered; }
}
/// The definition the bar was built from (the settings dialog reads the live one).
+ /// 本条构建时的配置定义(设置页读的是同一份实时对象)。
public FloatingBarDefinition Definition
{
get { return _bar; }
@@ -115,23 +172,27 @@ namespace pacs_win_uia.UI
/// True while the operator is dragging the bar. The manager keeps its "follow the anchor
/// window" ticks off the bar during a drag, otherwise the two would fight over the position.
///
+ /// 是否正在被拖动;拖动期间 manager 暂停“跟随锚定窗口”,避免两边争抢位置。
public bool IsDragging
{
get { return _dragging; }
}
/// The offsets the operator dragged the bar to, relative to the anchor window.
+ /// 把拖动后的位置回写成相对锚定窗口左上角的偏移(OffsetX/OffsetY)。
public void ApplyDraggedOffset(Point anchorTopLeft)
{
_bar.OffsetX = Left - anchorTopLeft.X;
_bar.OffsetY = Top - anchorTopLeft.Y;
}
+ /// 显示时不激活窗口,键盘焦点继续留在 PACS。
protected override bool ShowWithoutActivation
{
get { return true; }
}
+ /// 扩展样式:工具窗口、不激活、并启用 layered(供逐像素透明)。
protected override CreateParams CreateParams
{
get
@@ -146,6 +207,7 @@ namespace pacs_win_uia.UI
// ------------------------------------------------------------------ layout
+ /// 根据配置构出启用按钮的显示文案/提示文本(不计算坐标,坐标在 MeasureBar 里算)。
private void BuildLayout()
{
_buttons.Clear();
@@ -174,6 +236,7 @@ namespace pacs_win_uia.UI
}
}
+ /// 按文字宽度依次排布按钮,返回整条的客户区尺寸(含最小 24×24 下限)。
private Size MeasureBar()
{
int width = EdgePadding * 2;
@@ -196,12 +259,14 @@ namespace pacs_win_uia.UI
// ------------------------------------------------------------------ rendering
+ /// 句柄建立后立即首次渲染。
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
Render();
}
+ /// 尺寸变化后重绘(位图尺寸随窗体变)。
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
@@ -211,6 +276,7 @@ namespace pacs_win_uia.UI
}
}
+ /// layered 模式下窗口表面由 UpdateLayeredWindow 提供,跳过常规背景擦除以免闪烁。
protected override void OnPaintBackground(PaintEventArgs e)
{
// The window surface comes from UpdateLayeredWindow; normal painting would only flicker.
@@ -222,6 +288,7 @@ namespace pacs_win_uia.UI
base.OnPaintBackground(e);
}
+ /// 只有退化路径才走常规绘制;layered 路径改为画进位图。
protected override void OnPaint(PaintEventArgs e)
{
// Only the degraded path paints normally; the layered path renders into a bitmap instead.
@@ -233,6 +300,7 @@ namespace pacs_win_uia.UI
DrawBar(e.Graphics, false);
}
+ /// 处理 WM_ERASEBKGND(吞掉防闪烁)与 WM_NCHITTEST(圆角外穿透)。
protected override void WndProc(ref Message message)
{
const int WM_ERASEBKGND = 0x0014;
@@ -258,6 +326,7 @@ namespace pacs_win_uia.UI
base.WndProc(ref message);
}
+ /// 客户区点是否落在条的实际形状内(圆角外视为透明区)。
private bool IsInsideShape(int x, int y)
{
var shape = new Rectangle(0, 0, Width, Height);
@@ -268,6 +337,7 @@ namespace pacs_win_uia.UI
/// Draws the whole bar into an ARGB bitmap and hands it to the window. Called on every visual
/// change (hover, press, resize) — the bar is a few hundred pixels, so redrawing is free.
///
+ /// 把整条画进 ARGB 位图并交给窗口;悬停/按下/尺寸变化都调用它(像素少,重绘代价低)。
public void Render()
{
if (!IsHandleCreated || Width <= 0 || Height <= 0)
@@ -294,6 +364,7 @@ namespace pacs_win_uia.UI
/// Draws the bar. false is the degraded path: the same shapes,
/// fully opaque, with the whole window carrying the transparency.
///
+ /// 绘制背景圆角矩形与全部按钮;perPixelAlpha=false 为退化路径(形状同样、整体不透明)。
private void DrawBar(Graphics graphics, bool perPixelAlpha)
{
int backgroundAlpha = perPixelAlpha ? ToAlpha(_bar.EffectiveBackgroundOpacity) : SolidAlpha;
@@ -346,6 +417,7 @@ namespace pacs_win_uia.UI
/// Hands the bitmap to the window. If per-pixel alpha is unavailable the bar degrades to a
/// whole-window opacity (still drawn by the tool, just one alpha for everything).
///
+ /// 把位图提交给窗口(UpdateLayeredWindow);不可用时退化为整窗不透明度并常规重绘。
private void ApplyBitmap(Bitmap bitmap, int backgroundAlpha)
{
IntPtr screenDc = IntPtr.Zero;
@@ -404,11 +476,13 @@ namespace pacs_win_uia.UI
}
finally
{
+ // 恢复原位图并释放:GetHbitmap/SelectObject 得到的 GDI 资源必须回收,否则句柄泄漏。
if (previous != IntPtr.Zero)
{
NativeMethods.SelectObject(memoryDc, previous);
}
+ // 本方法创建的 HBITMAP 必须 DeleteObject。
if (hBitmap != IntPtr.Zero)
{
NativeMethods.DeleteObject(hBitmap);
@@ -426,12 +500,14 @@ namespace pacs_win_uia.UI
}
}
+ /// 把 1~100 的不透明度百分比换算成 1~255 的 alpha。
private static int ToAlpha(int percent)
{
int clamped = Math.Max(1, Math.Min(100, percent));
return clamped * 255 / 100;
}
+ /// 构造圆角矩形路径(半径过大时退化为普通矩形)。
private static GraphicsPath RoundedRect(Rectangle bounds, int radius)
{
var path = new GraphicsPath();
@@ -452,6 +528,7 @@ namespace pacs_win_uia.UI
// ------------------------------------------------------------------ input
+ /// 客户区坐标命中的按钮索引,未命中返回 -1。
private int HitTest(Point client)
{
for (int index = 0; index < _buttons.Count; index++)
@@ -465,6 +542,7 @@ namespace pacs_win_uia.UI
return -1;
}
+ /// 左键按下:命中按钮则记为按下;点在空白处则进入拖动模式。
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
@@ -483,6 +561,7 @@ namespace pacs_win_uia.UI
Render();
}
+ /// 鼠标移动:拖动中直接改窗体屏幕位置;否则更新悬停高亮与 tooltip。
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
@@ -502,6 +581,7 @@ namespace pacs_win_uia.UI
}
}
+ /// 左键抬起:只有“按下与抬起在同一按钮”才算点击,随后触发 ActionInvoked。
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
@@ -528,6 +608,7 @@ namespace pacs_win_uia.UI
}
}
+ /// 鼠标离开:清除悬停高亮并收起 tooltip。
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
@@ -541,6 +622,7 @@ namespace pacs_win_uia.UI
_shownTooltip = null;
}
+ /// 丢失鼠标捕获(如别处抢焦点)时清掉按下态,避免按钮卡住高亮。
protected override void OnMouseCaptureChanged(EventArgs e)
{
base.OnMouseCaptureChanged(e);
@@ -551,6 +633,7 @@ namespace pacs_win_uia.UI
}
}
+ /// 在悬停按钮下方显示 tooltip(文本未变则不重复弹)。
private void UpdateTooltip(int index)
{
if (index < 0)
@@ -571,6 +654,7 @@ namespace pacs_win_uia.UI
_tooltip.Show(text, this, new Point(bounds.Left, bounds.Bottom + 4), 8000);
}
+ /// 释放:一并销毁复用的 ToolTip。
protected override void Dispose(bool disposing)
{
if (disposing)
diff --git a/src/pacs_win_uia/UI/HighlightOverlayForm.cs b/src/pacs_win_uia/UI/HighlightOverlayForm.cs
index a8e8fa5..2b84ef8 100644
--- a/src/pacs_win_uia/UI/HighlightOverlayForm.cs
+++ b/src/pacs_win_uia/UI/HighlightOverlayForm.cs
@@ -1,3 +1,22 @@
+// ============================================================================
+// HighlightOverlayForm —— 高亮框窗体(只负责画一个红框)
+//
+// 职责:
+// 一个非激活、点击穿透、置顶的窗体,画一条 3px 红边矩形,用来圈住被跟随的控件。
+// 位置与显示/隐藏由 HighlightFollower 驱动,本类不含任何跟随逻辑。
+//
+// 被谁调用:HighlightFollower._overlay(唯一持有者)。
+//
+// 节拍与线程:纯 UI 线程;跟随节拍在 HighlightFollower(120ms),本窗体只被 ShowHighlight/Hide 调用。
+//
+// 不抢焦点/点击穿透的实现:
+// · CreateParams 设 WS_EX_TOOLWINDOW|WS_EX_NOACTIVATE|WS_EX_TRANSPARENT(透明=鼠标穿透)。
+// · WM_NCHITTEST 直接返回 HTTRANSPARENT;WM_MOUSEACTIVATE 返回 MA_NOACTIVATE。
+// · ShowWithoutActivation=true,显示时不激活。
+// · TransparencyKey/BackColor 同色(Magenta)抠掉内部,只留红色边框可见。
+//
+// “要改什么就改哪里”:边框样式 → OnPaint;穿透/激活行为 → WndProc / CreateParams。
+// ============================================================================
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
@@ -9,8 +28,10 @@ namespace pacs_win_uia.UI
///
/// A non-activating, click-through highlight rectangle.
///
+ /// 非激活、点击穿透的高亮矩形窗体。
public sealed class HighlightOverlayForm : Form
{
+ /// 初始化:无边框、不进任务栏、置顶;用 Magenta 抠透明并设整体 85% 不透明度。
public HighlightOverlayForm()
{
FormBorderStyle = FormBorderStyle.None;
@@ -22,11 +43,13 @@ namespace pacs_win_uia.UI
Opacity = 0.85D;
}
+ /// 显示时不激活窗口。
protected override bool ShowWithoutActivation
{
get { return true; }
}
+ /// 扩展样式:工具窗口、不激活、鼠标穿透。
protected override CreateParams CreateParams
{
get
@@ -39,6 +62,7 @@ namespace pacs_win_uia.UI
}
}
+ /// 让鼠标点击穿透(HTTRANSPARENT),并拒绝激活(MA_NOACTIVATE)。
protected override void WndProc(ref Message message)
{
if (message.Msg == NativeMethods.WM_NCHITTEST)
@@ -56,6 +80,7 @@ namespace pacs_win_uia.UI
base.WndProc(ref message);
}
+ /// 按屏幕矩形显示/移动高亮框;矩形过小则直接隐藏。
public void ShowHighlight(Rectangle bounds)
{
if (bounds.Width < 1 || bounds.Height < 1)
@@ -73,11 +98,13 @@ namespace pacs_win_uia.UI
Invalidate();
}
+ /// 隐藏高亮框。
public void HideHighlight()
{
Hide();
}
+ /// 画 3px 红边:内缩 1px,避免被窗体边缘裁掉。
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
@@ -89,6 +116,7 @@ namespace pacs_win_uia.UI
}
}
+ /// 释放前先隐藏,避免残影。
protected override void Dispose(bool disposing)
{
if (disposing)
diff --git a/src/pacs_win_uia/UI/MainForm.cs b/src/pacs_win_uia/UI/MainForm.cs
index ecf446a..fb3f9e1 100644
--- a/src/pacs_win_uia/UI/MainForm.cs
+++ b/src/pacs_win_uia/UI/MainForm.cs
@@ -17,6 +17,66 @@ using pacs_win_uia.Models;
using pacs_win_uia.Services;
using pacs_win_uia.UI;
+/* ============================================================================
+ * MainForm —— 主界面外壳(第一/二阶段)
+ * ----------------------------------------------------------------------------
+ * 职责:
+ * 1) 枚举本机可见的顶级窗口(左栏「窗口列表」);
+ * 2) 对选中窗口 / 拾取到的控件读取"统一控件树"(中栏「控件树」标签页);
+ * 3) 把选中的节点或监控条目在「控件属性」网格里展示/编辑,并维护「控件监控列表」(右栏)。
+ * 本窗体是只读检查器:除「尝试激活目标无障碍」和悬浮按钮的自定义命令外,不修改目标进程状态。
+ *
+ * 三个主流程(自上而下):
+ * A. 窗口枚举:RefreshWindows() → ApplyWindowFilter()(重建列表、按标题/进程/PID 过滤、按 HWND 恢复选中)。
+ * B. 控件树读取:InspectSelectedWindow() / 拾取 → BeginTreeRead()(后台)→ ApplyTree() → RebuildTreeView()。
+ * C. 属性/监控:ShowNodeProperties() / ControlTreeOnAfterSelect() 驱动 _propertyGrid 与 _monitorEditor。
+ * 另有两条派生支线:列表读取(ReadSelectedList → ApplyListResult)、按 path 定位(LocateByPath)。
+ *
+ * 界面布局(三栏,由 _splitMain / _splitRight / _splitRightColumn 三个分隔条划分):
+ * 左栏 = 窗口搜索框 + 窗口列表(_windowList)+ 计数标签。
+ * 中栏 = 结果标签页 _resultTabs:Tab1「控件树」(_controlTree + _treeSearchPanel),Tab2「列表结果」(_listResultGrid)。
+ * 右栏 = 上:控件属性 PropertyGrid(_propertyGrid,外包 ScrollHostPanel);下:控件监控列表(_monitorEditor)。
+ * 再加顶部工具栏与底部状态栏(_statusText)。分隔条比例见 ApplyInitialSplitterDistances()。
+ *
+ * 关键状态字段的生命周期:
+ * _windows —— 每次 RefreshWindows() 重新赋值,是列表重建的数据源。
+ * _currentTreeRoot —— 每次 ApplyTree() / LiveTreeTimerOnTick() 整体替换;ClearInspectionState() 置空。
+ * _currentNode —— 跟随控件树选中项 / 监控定位变化(ShowNodeProperties() 设置)。
+ * _currentElement —— 选中节点的 UIA 元素快照,决定能否「读取列表」「加入监控」。
+ * _treeRootHandle —— 当前树的根窗口句柄;非零表示"有树",IntPtr.Zero 表示尚未选窗。
+ * _inspectionSequence —— 控件树读取的单调序号,用于丢弃过期回调(见下)。
+ * _pickSession —— 每次拾取自增,用于判断"本次拾取是否已自动加过监控"。
+ * _pendingTreeSelection —— 待新树读完后要选中的节点(拾取 / 跨窗口定位用)。
+ *
+ * 线程模型:
+ * - UI 线程:所有控件读写、_propertyGrid、_monitorEditor、_controlTree 的更新。
+ * - 后台线程:控件树读取、列表读取、坐标重解析(Task.Factory.StartNew + LongRunning;
+ * 跨进程 Provider 调用可能卡死且不可中断,不能用线程池线程)。
+ * - 后台结果一律通过 BeginInvoke 回到 UI 线程,且先比对 sequence / handle 再应用(丢弃"旧结果")。
+ *
+ * 定时器一览:
+ * _autoInspectTimer (350ms) —— 窗口列表选中后的防抖,到点触发一次检查(AutoInspectTimerOnTick)。
+ * _treeReadTimer (500ms) —— 仅在树读取期间运行,更新状态栏"正在读取…已 N 秒"。
+ * _liveTreeTimer (可配) —— 常驻;定时后台重读当前树,让框随界面变化(LiveTreeTimerOnTick)。
+ * _stateTimer —— 本窗体没有该字段;监控项的定时刷新由 ControlMonitorEditorControl 内部定时器承担。
+ * (另:ActivateTargetAccessibility 里临时创建一个 900ms 的一次性 Timer 用于延迟重读,用完即 Dispose。)
+ *
+ * 路径定位:当前唯一格式是 XPath(ControlPath.IsXPath);旧格式已停用,
+ * LocateByPath() / PathLocateForm 会明确报出"仅支持 XPath / 不支持旧格式"。
+ *
+ * 「要改 X 就看哪」索引:
+ * 改窗口列表 / 过滤 / 高亮 → RefreshWindows / ApplyWindowFilter / FindTopmostPrimaryHandle
+ * 改控件树读取与来源 → BeginTreeRead / GetSelectedTreeSource / RereadCurrentTree / LiveTreeTimerOnTick
+ * 改实时刷新节奏 → _liveTreeTimer.Interval(设置里改)、LiveTreeTimerOnTick
+ * 改树的显示 / 搜索 / 保留状态 → RebuildTreeView / ReconcileTreeView / BuildTreeItem / NavigateTreeMatch
+ * 改属性网格显示 → ShowNodeProperties / SelectedObjectFor / SyncSelectedTreeProperties
+ * 改拾取流程 → StartPicker / PickerOnPicked / ApplyPickResult / ScheduleDeeperPickRetry
+ * 改按 path 定位 / 画框 → LocateByPath / ShowFrameFor / MonitorEditorOnControlLocated / CanShowLocateFrame
+ * 改列表读取 → ReadSelectedList / ApplyListResult / BuildListGridTable / LogStructureDiagnostics
+ * 改监控定位与跨窗口联动 → EnsureTreeShows / SelectTreeNodeFor / ApplyPendingTreeSelection
+ * 改布局 → MainFormOnLoad / ApplyScreenFitting / ApplyInitialSplitterDistances / VerifyLayout
+ * ========================================================================= */
+
namespace pacs_win_uia
{
///
@@ -24,123 +84,237 @@ namespace pacs_win_uia
///
public sealed class MainForm : Form
{
+ // 控件树读取的默认限制(可在「设置」里覆盖):最大递归深度。
private const int TreeMaxDepth = 8;
+ // 控件树读取的默认限制(可在「设置」里覆盖):最大节点数。
private const int TreeMaxNodes = 2000;
+ // 列表读取失败时做结构诊断,向上追溯的祖先层数。
private const int DiagnosticsAncestorDepth = 4;
+ // 结构诊断打印的被拾取元素的直接子元素个数上限。
private const int DiagnosticsChildCount = 10;
+ // 同时进行的后台读取任务上限;超过则拒绝新读取,避免目标无响应时任务堆积。
private const int MaxConcurrentReads = 4;
+ // 「尝试激活目标无障碍」后,等待目标重建树的延迟(毫秒)。
private const int ActivationRetryDelayMs = 400;
+ // 拾取只拿到顶层窗口时,按同一坐标重探一次前的延迟(毫秒)。
private const int DeeperPickRetryDelayMs = 600;
+ // 窗口自适应屏幕时四周预留的边距(像素)。
private const int ScreenMargin = 40;
+ // 控件树读取的默认超时(可在「设置」里覆盖)。
private static readonly TimeSpan TreeTimeout = TimeSpan.FromSeconds(10);
+ // 窗口的期望初始尺寸。
private static readonly Size PreferredWindowSize = new Size(1400, 850);
+ // 窗口枚举 / 按句柄取窗口信息 / 截图的底层服务。
private readonly NativeWindowService _windowService;
+ // 跨进程 UIA 读取服务(元素属性、子元素、结构诊断)。
private readonly UiAutomationService _uiAutomationService;
+ // 控件树导出为 JSON 的导出器。
private readonly ControlTreeExporter _treeExporter;
+ // 左栏:可见顶级窗口列表(各列为 标题/进程/PID/HWND/类名/可见/最小化)。
private readonly ListView _windowList;
+ // 左栏:窗口过滤框,按标题/进程名/PID 过滤(见 MatchesFilter)。
private readonly TextBox _windowSearchBox;
+ // 左栏:窗口计数标签("显示 x / y")。
private readonly Label _windowCountLabel;
+ // 中栏:控件树 TreeView;每个 TreeNode.Tag 挂一个 ControlTreeNode。
private readonly TreeView _controlTree;
+ // 中栏:列表结果表格(列表读取结果展示)。
private readonly DataGridView _listResultGrid;
+ // 中栏:结果标签页容器(控件树 / 列表结果两个页)。
private readonly TabControl _resultTabs;
+ // 中栏:列表结果表格的 DataTable 数据源。
private readonly DataTable _listResultTable;
+ // 中栏:「列表结果」标签页。
private readonly TabPage _listResultTab;
+ // 中栏:「控件树」标签页。
private readonly TabPage _controlTreeTab;
+ // 右栏上:控件属性网格,同时充当监控条目编辑器(SelectedObject 可能是 ControlMonitorDefinition)。
private readonly PropertyGrid _propertyGrid;
+ // 控件树读取服务(可指定来源与限制,在后台线程调用)。
private readonly ControlTreeService _controlTreeService;
+ // 「尝试激活目标无障碍」服务(会改动目标状态,仅在用户点击时调用)。
private readonly AccessibilityActivationService _activationService;
+ // 右栏下:控件监控列表编辑控件(自带刷新定时器与增删改)。
private readonly ControlMonitorEditorControl _monitorEditor;
+ // 底部状态栏(只读多行 TextBox)。
private readonly TextBox _statusText;
+ // 工具栏:「刷新窗口」按钮。
private readonly Button _refreshButton;
+ // 工具栏:「检查选中窗口」按钮(无选中时禁用)。
private readonly Button _inspectButton;
+ // 杂项菜单:「导出控件树」。
private readonly ToolStripMenuItem _exportTreeItem;
+ // 杂项菜单:「读取选中控件列表」。
private readonly ToolStripMenuItem _readListItem;
+ // 杂项菜单:「导出列表 JSON/CSV」。
private readonly ToolStripMenuItem _exportListItem;
+ // 工具栏:「拾取控件」按钮(拾取中切换为取消)。
private readonly Button _pickButton;
+ // 工具栏:控件树来源下拉(0 自动 / 1 UIA / 2 MSAA / 3 Win32)。
private readonly ComboBox _treeSourceCombo;
+ // 左栏:窗口列表标题。
private readonly Label _windowListCaption;
+ // 右栏:控件属性标题(会显示当前页面特征)。
private readonly Label _propertyCaption;
+ // 右栏:控件监控列表标题。
private readonly Label _monitorCaption;
+ // 中栏:控件树搜索面板(搜索条件、仅显示匹配、匹配导航)。
private readonly ControlTreeSearchPanel _treeSearchPanel;
+ // 中栏:列表结果页顶部的说明标签。
private readonly Label _listResultHint;
+ // 工具栏:「设置」按钮。
private readonly Button _settingsButton;
+ // 杂项菜单:「窗口截图」。
private readonly ToolStripMenuItem _screenshotItem;
+ // 杂项菜单:「OCR 读取」。
private readonly ToolStripMenuItem _ocrItem;
+ // 工具栏:「杂项 ▾」按钮(点击弹出 _miscMenu)。
private readonly Button _miscButton;
+ // 杂项下拉菜单(承载低频功能项)。
private readonly ContextMenuStrip _miscMenu;
+ // 消息过滤器:Shift+滚轮横向滚动(全局注册,退出时移除)。
private readonly ShiftWheelScroll _shiftWheel = new ShiftWheelScroll();
+ // 属性网格的滚动宿主(避免 PropertyGrid 内部滚动问题)。
private readonly ScrollHostPanel _propertyHost;
+ // 杂项菜单:「复制页面特征」。
private readonly ToolStripMenuItem _copyFeaturesItem;
+ // 杂项菜单:「按 path 定位…」。
private readonly ToolStripMenuItem _locateByPathItem;
+ // 杂项菜单:「绘制所有控件框」(可勾选的实时控件框开关)。
private readonly ToolStripMenuItem _nodeMapItem;
+ // 截图服务(按截图方式与完整性返回结果)。
private readonly ScreenshotService _screenshotService;
+ // OCR 读取上下文;设置变更后由 ShowSettings() 重建,null 表示 OCR 未启用。
private OcrReadContext _ocrContext;
+ // 当前在控件树里选中的节点(未选中为 null);决定截图/OCR/复制特征是否可用。
private ControlTreeNode _currentNode;
+ // 设置读写(JSON 文件)。
private readonly Services.AppSettingsStore _settingsStore;
+ // 命令执行器(悬浮按钮命令、启动/退出钩子)。
private readonly Services.CommandRunner _commandRunner;
+ // 定位高亮框的跟随器(跨进程算坐标、跟随拖动,见 BuildBoundsResolver)。
private readonly HighlightFollower _locateFollower;
+ // 「绘制所有控件框」的覆盖层窗体。
private readonly NodeMapOverlayForm _nodeMapOverlay;
+ // 按监控定义重新定位控件的服务(用于容错定位与坐标重解析)。
private readonly ControlLocatorService _locatorService = new ControlLocatorService();
+ // 当前高亮框对应的监控定义(用于"再点一次隐藏"的判断)。
private ControlMonitorDefinition _locatedDefinition;
+ // 当前高亮框对应的树节点。
private ControlTreeNode _locatedNode;
/// Node to select once the tree of its own window has been read (see ApplyTree).
+ // 待新树读完后要选中的节点(拾取或跨窗口定位时设置,见 ApplyTree/ApplyPendingTreeSelection)。
private ControlTreeNode _pendingTreeSelection;
/// Falls back to a tree rooted at the picked element when the window tree lacks it.
+ // 记录"已自动加过监控"的拾取会话号,避免同一会话重复添加。
private int _autoAddedPickSession = -1;
/// True while the tree source is switched programmatically (no re-read of the old root).
+ // 程序化切换来源时为 true,避免引发对旧根的重读。
private bool _suppressTreeSourceEvents;
+ // 本次拾取是否要连带展开被拾取节点的子节点(ApplyTree 消费后复位)。
private bool _expandPickedTree;
+ // 当前设置(设置对话框保存后整体重载)。
private AppSettings _settings;
+ // 悬浮条管理器(可见性由页面条件决定)。
private FloatingBarManager _floatingBars;
+ // 当前搜索命中的树节点集合(供 ▲/▼ 导航;RebuildTreeView 时重建)。
private readonly List _treeMatches = new List();
+ // 工具栏:「尝试激活目标无障碍」按钮。
private readonly Button _activateButton;
+ // 工具栏:拾取预览标签(显示当前鼠标下窗口/UIA 信息)。
private readonly Label _pickerPreviewLabel;
+ // 探测服务:按屏幕坐标探测窗口/UIA/MSAA 元素(拾取用)。
private readonly TargetProbeService _probeService;
+ // 列表读取服务(标准 UIA 列表模式)。
private readonly ListReaderService _listReaderService;
+ // 列表读取结果的 JSON/CSV 导出器。
private readonly ListResultExporter _listResultExporter;
+ // 十字拾取器(拾取期间隐藏主窗体)。
private readonly CrosshairPicker _picker;
+ // 防抖定时器:选中窗口后延迟触发自动检查。
private readonly System.Windows.Forms.Timer _autoInspectTimer;
+ // 状态提示定时器:树读取期间刷新"正在读取…已 N 秒"。
private readonly System.Windows.Forms.Timer _treeReadTimer;
+ // 实时刷新定时器:常驻,定时后台重读当前树。
private readonly System.Windows.Forms.Timer _liveTreeTimer;
+ // 实时重读是否正在进行(防止叠加)。
private bool _liveTreeReadInFlight;
+ // 正在由 ControlTreeReconciler 恢复树状态时为 true,抑制 AfterSelect 副作用。
private bool _restoringTreeState;
+ // 树视图与模型的增量协调器(保留选择/展开状态)。
private ControlTreeReconciler _treeReconciler;
+ // 拾取流程中"待自动加入监控"标志(在 ApplyPickResult 设置,ApplyPendingTreeSelection 消费)。
private bool _autoAddPendingPick;
+ // XPath 搜索命中的节点集合(与 _treeMatches 不同,这是模型层命中)。
private HashSet _pathSearchMatches;
+ // 上次实时树刷新完成的时间(未用于节流,仅供参考)。
private DateTime _lastLiveTreeUtc;
+ // 本次实时树读取开始时间。
private DateTime _liveTreeStartedUtc;
+ // 本次显式树读取开始时间(default 表示不在读取中)。
private DateTime _treeReadStartedUtc;
+ // 本次树读取的标签(显示在状态栏)。
private string _treeReadLabel;
+ // 分隔条是否已按最终布局初始化过(Shown 时设置一次)。
private bool _splittersInitialized;
+ // 外层分隔条:左栏 | 其余。
private readonly SplitContainer _splitMain;
+ // 中层分隔条:中栏 | 右栏。
private readonly SplitContainer _splitRight;
+ // 右栏分隔条:属性网格 | 监控列表。
private readonly SplitContainer _splitRightColumn;
+ // 最近一次列表读取结果(导出时用,切换节点时清空)。
private ListReadResult _lastListResult;
+ // 窗体级取消源:关闭时取消所有关联的后台读取。
private readonly CancellationTokenSource _shutdown = new CancellationTokenSource();
+ // 当前控件树读取的取消源(新读取前取消并置空旧的)。
private CancellationTokenSource _inspectionCancellation;
+ // 当前列表读取的取消源。
private CancellationTokenSource _listReadCancellation;
+ // 列表读取的单调序号,用于丢弃过期回调(每次取消也自增)。
private int _listReadSequence;
+ // 当前控件树模型根(ApplyTree/实时刷新赋值;与 _currentTreeRoot 常相同)。
private ControlTreeNode _currentTree;
+ // 当前控件树模型根(对外主用)。
private ControlTreeNode _currentTreeRoot;
+ // 当前树的根窗口句柄;IntPtr.Zero 表示尚未选窗。
private IntPtr _treeRootHandle = IntPtr.Zero;
+ // 当前树使用的来源(null = 自动)。
private ControlTreeSource? _currentTreeSource;
+ // 树重读时复用的 UIA 根元素(可能为 null)。
private AutomationElement _treeUiaRoot;
+ // 当前树对应的窗口信息。
private NativeWindowInfo _treeWindow;
+ // 当前选中节点的 UIA 元素快照(决定能否读列表/加监控)。
private UiaElementInfo _currentElement;
+ // 最近一次检查的窗口信息。
private NativeWindowInfo _inspectedWindow;
+ // 最近一次枚举到的全部可见顶级窗口(RefreshWindows 重新赋值)。
private IList _windows = new List();
+ // 控件树读取的单调序号,用于丢弃过期回调。
private int _inspectionSequence;
+ // 拾取会话号,每次拾取自增。
private int _pickSession;
+ // 正在进行的后台读取任务数(受 MaxConcurrentReads 限制)。
private int _activeReads;
+ // 抑制窗口列表选择事件时为 true(重建列表/程序化选中时避免误触发)。
private bool _suppressSelectionEvents;
+ // 上次自动检查过的窗口句柄(相同且已有树时跳过重复检查)。
private IntPtr _lastAutoInspectedHandle = IntPtr.Zero;
+ // 拾取前记录的前台窗口句柄,拾取结束后把焦点交还给它。
private IntPtr _foregroundBeforePick = IntPtr.Zero;
+ // 最近一次列表读取的目标描述(日志用)。
private string _lastListReadElement = "(无)";
+ ///
+ /// 构造主界面:创建服务、悬浮条与三个定时器,搭建工具栏与三栏布局,并挂钩事件。
+ /// 首次数据加载放在 Shown(MainFormOnShown)里,因为分隔条比例依赖窗体的最终尺寸。
+ ///
public MainForm()
{
+ // ---- 服务与运行期状态 ----
_windowService = new NativeWindowService();
_uiAutomationService = new UiAutomationService();
_treeExporter = new ControlTreeExporter();
@@ -165,6 +339,7 @@ namespace pacs_win_uia
_picker.PreviewChanged += PickerOnPreviewChanged;
_picker.Picked += PickerOnPicked;
_picker.Canceled += PickerOnCanceled;
+ // ---- 三个定时器:防抖检查 / 读取状态提示 / 实时刷新(实时刷新立即启动)----
_autoInspectTimer = new System.Windows.Forms.Timer { Interval = 350 };
_autoInspectTimer.Tick += AutoInspectTimerOnTick;
_treeReadTimer = new System.Windows.Forms.Timer { Interval = 500 };
@@ -173,15 +348,18 @@ namespace pacs_win_uia
_liveTreeTimer.Tick += LiveTreeTimerOnTick;
_liveTreeTimer.Start();
+ // ---- 全局输入:Ctrl+F 跳搜索框、Shift+滚轮横向滚动 ----
KeyPreview = true;
KeyDown += MainFormOnKeyDown;
Application.AddMessageFilter(_shiftWheel);
+ // ---- 窗体外观(初始尺寸,Shown 时再按屏幕自适应)----
Text = "PACS Windows UI Automation Inspector - 第一/二阶段";
StartPosition = FormStartPosition.CenterScreen;
MinimumSize = new Size(900, 600);
Size = PreferredWindowSize;
+ // ---- 顶部工具栏 ----
var toolbar = new FlowLayoutPanel
{
Dock = DockStyle.Top,
@@ -254,6 +432,7 @@ namespace pacs_win_uia
toolbar.Controls.Add(_pickerPreviewLabel);
toolbar.Controls.Add(limitationLabel);
+ // ---- 三栏内容控件:左栏窗口列表 / 中栏结果标签页 / 右栏属性+监控 ----
_windowSearchBox = new TextBox { Dock = DockStyle.Top };
_windowCountLabel = new Label
{
@@ -377,6 +556,7 @@ namespace pacs_win_uia
monitorPanel.Controls.Add(_monitorEditor);
monitorPanel.Controls.Add(_monitorCaption);
+ // ---- 三栏布局:三个 SplitContainer 嵌套成套 ----
// Three columns: window list | 控件树/列表结果 | 属性 + 控件监控列表.
// Min sizes are applied with the splitter distances in ApplyInitialSplitterDistances:
// setting them here would validate against the default SplitterDistance and throw.
@@ -408,6 +588,7 @@ namespace pacs_win_uia
Controls.Add(_statusText);
Controls.Add(toolbar);
+ // ---- 事件挂钩 ----
_refreshButton.Click += delegate { RefreshWindows(); };
_pickButton.Click += delegate { StartPicker(); };
_inspectButton.Click += delegate { InspectSelectedWindow(); };
@@ -648,6 +829,7 @@ namespace pacs_win_uia
}
}
+ // 执行悬浮按钮自定义命令(30 秒超时),结果写入状态栏。
private void RunFloatingCommand(FloatingButtonDefinition button)
{
if (string.IsNullOrWhiteSpace(button.CommandLine))
@@ -682,6 +864,7 @@ namespace pacs_win_uia
base.WndProc(ref message);
}
+ // 窗体加载:按屏幕自适应尺寸、重载悬浮条,并执行配置的启动命令。
private void MainFormOnLoad(object sender, EventArgs e)
{
ApplyScreenFitting();
@@ -750,6 +933,7 @@ namespace pacs_win_uia
AppLog.Info("界面布局检查完成:控件树节点 " + CountControls(this) + " 个,异常区域 " + missing + " 个。");
}
+ // 布局自检用的区域描述(名称、控件、最小宽高)。
private struct LayoutRegion
{
internal LayoutRegion(string name, Control control, int minimumWidth, int minimumHeight)
@@ -766,6 +950,7 @@ namespace pacs_win_uia
internal readonly int MinimumHeight;
}
+ // 判断控件是否真挂在窗体可视树上(未加入容器的控件不会显示)。
private bool IsInVisualTree(Control control)
{
Control current = control;
@@ -782,6 +967,7 @@ namespace pacs_win_uia
return false;
}
+ // 递归统计控件数量(仅用于布局检查日志)。
private static int CountControls(Control parent)
{
int count = 1;
@@ -793,6 +979,7 @@ namespace pacs_win_uia
return count;
}
+ // 首次显示:初始化分隔条比例、做一次布局自检,然后枚举窗口。
private void MainFormOnShown(object sender, EventArgs e)
{
// The splitter distances depend on the final, possibly maximized, layout.
@@ -828,6 +1015,7 @@ namespace pacs_win_uia
};
}
+ // 按当前屏幕工作区自适应窗口尺寸与位置(避免超出屏幕或过于局促)。
private void ApplyScreenFitting()
{
Rectangle workingArea = Screen.FromControl(this).WorkingArea;
@@ -852,6 +1040,7 @@ namespace pacs_win_uia
ApplySplitterLayout(_splitRightColumn, Orientation.Horizontal, 0.52D, 160, 200, "属性/监控列表");
}
+ // 先放开最小尺寸再设 SplitterDistance,最后收紧最小尺寸(否则会被校验抛异常)。
private static void ApplySplitterLayout(
SplitContainer container,
Orientation orientation,
@@ -890,6 +1079,7 @@ namespace pacs_win_uia
// ------------------------------------------------------------------ window list
+ // 枚举可见顶级窗口写入 _windows,再重建列表(不完整的枚举会如实报错)。
private void RefreshWindows()
{
try
@@ -1019,6 +1209,7 @@ namespace pacs_win_uia
return IntPtr.Zero;
}
+ // 把一个窗口信息转成列表行(SubItem 顺序与列标题一致,Tag 挂回窗口对象)。
private static ListViewItem CreateWindowItem(NativeWindowInfo window)
{
var item = new ListViewItem(window.Title ?? string.Empty);
@@ -1038,6 +1229,7 @@ namespace pacs_win_uia
return window.IsVisible && !string.IsNullOrWhiteSpace(window.Title);
}
+ // 过滤匹配:标题、PID 或进程名任一包含过滤串即命中(空过滤串全部命中)。
private static bool MatchesFilter(NativeWindowInfo window, string filter)
{
if (string.IsNullOrEmpty(filter))
@@ -1060,6 +1252,7 @@ namespace pacs_win_uia
window.ProcessName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0;
}
+ // 按 HWND 在列表里选中对应行(临时抑制选择事件,避免触发自动检查)。
private bool SelectWindowItem(IntPtr handle)
{
if (handle == IntPtr.Zero)
@@ -1156,6 +1349,7 @@ namespace pacs_win_uia
return false;
}
+ // 窗口列表选择变化:更新按钮可用性、清空检查状态、必要时防抖触发自动检查。
private void WindowListOnSelectedIndexChanged(object sender, EventArgs e)
{
bool hasSelection = _windowList.SelectedItems.Count > 0;
@@ -1207,6 +1401,7 @@ namespace pacs_win_uia
seconds, _treeReadLabel), null);
}
+ // 防抖到点:对当前选中窗口执行一次检查(同一窗口且已有树时跳过)。
private void AutoInspectTimerOnTick(object sender, EventArgs e)
{
_autoInspectTimer.Stop();
@@ -1230,6 +1425,7 @@ namespace pacs_win_uia
InspectWindow(window);
}
+ // 清空与当前窗口/控件树相关的一切检查状态(切换窗口、拾取前后、关闭时调用)。
private void ClearInspectionState()
{
_treeReadTimer.Stop();
@@ -1261,6 +1457,7 @@ namespace pacs_win_uia
// ------------------------------------------------------------------ picker
+ // 启动/取消十字拾取器;启动前记录前台窗口并隐藏主界面,避免拾取到本工具自身。
private void StartPicker()
{
if (_picker.IsPicking)
@@ -1278,6 +1475,7 @@ namespace pacs_win_uia
HideLocateFrame(null);
_foregroundBeforePick = NativeMethods.GetForegroundWindow();
AppLog.Info("拾取开始:隐藏主界面;原前台窗口=" + NativeWindowInfo.FormatHandle(_foregroundBeforePick));
+ // 主界面必须先隐藏,否则拾取器会命中本工具自己的窗口。
Hide();
try
{
@@ -1318,6 +1516,7 @@ namespace pacs_win_uia
}
}
+ // 拾取预览:鼠标移动时更新工具栏上的目标信息(原生窗口 + UIA + 坐标)。
private void PickerOnPreviewChanged(object sender, PointPickResult result)
{
if (result == null)
@@ -1334,6 +1533,7 @@ namespace pacs_win_uia
_pickerPreviewLabel.Text = string.Format("拾取预览:{0}; {1}; 坐标 ({2},{3})", native, uia, result.ScreenX, result.ScreenY);
}
+ // 拾取完成:恢复主界面、推进会话号、应用结果,必要时安排"更深层重探"。
private void PickerOnPicked(object sender, PointPickResult result)
{
RestoreAfterPick();
@@ -1424,6 +1624,7 @@ namespace pacs_win_uia
+ ",这样节点一定在同一棵树里。", null);
}
+ // 把拾取结果转成节点:同步窗口列表选中、设定待选节点,并从顶层窗口起读控件树。
private void ApplyPickResult(PointPickResult result)
{
ControlTreeNode pickedNode = BuildPickedNode(result);
@@ -1530,6 +1731,7 @@ namespace pacs_win_uia
TaskScheduler.Default);
}
+ // 拾取取消:恢复主界面并复位按钮与提示。
private void PickerOnCanceled(object sender, EventArgs e)
{
RestoreAfterPick();
@@ -1540,6 +1742,7 @@ namespace pacs_win_uia
// ------------------------------------------------------------------ tree
+ // 「检查选中窗口」:对窗口列表选中项发起一次控件树读取。
private void InspectSelectedWindow()
{
NativeWindowInfo window = GetSelectedWindow();
@@ -1552,6 +1755,7 @@ namespace pacs_win_uia
InspectWindow(window);
}
+ // 对指定窗口发起控件树读取,先清空旧列表结果并复位相关按钮。
private void InspectWindow(NativeWindowInfo window)
{
if (window == null || window.Handle == IntPtr.Zero)
@@ -1593,6 +1797,7 @@ namespace pacs_win_uia
return;
}
+ // 取消上一次读取;序号自增后,旧回调的 sequence 不再匹配会被直接丢弃。
CancelInspection();
_inspectionCancellation = CancellationTokenSource.CreateLinkedTokenSource(_shutdown.Token);
CancellationToken token = _inspectionCancellation.Token;
@@ -1632,6 +1837,7 @@ namespace pacs_win_uia
Timeout = _settings == null ? TreeTimeout : TimeSpan.FromSeconds(_settings.Ui.TreeTimeoutSeconds)
};
+ // 后台线程读取;LongRunning 专用线程,避免卡死的跨进程 Provider 调用占用线程池。
Task task = Task.Factory.StartNew(
delegate
{
@@ -1665,6 +1871,7 @@ namespace pacs_win_uia
{
Interlocked.Decrement(ref _activeReads);
stopwatch.Stop();
+ // 先比对序号:窗体已销毁、句柄已失效或已被更新的读取取代时,丢弃这份旧结果。
if (IsDisposed || !IsHandleCreated || sequence != _inspectionSequence)
{
return;
@@ -1717,6 +1924,7 @@ namespace pacs_win_uia
TaskScheduler.Default);
}
+ // 实时刷新:后台重读当前树,仅在序号与根句柄未变时替换模型与树视图。
private void LiveTreeTimerOnTick(object sender, EventArgs e)
{
if (IsDisposed || _shutdown.IsCancellationRequested || _picker.IsPicking ||
@@ -1755,6 +1963,7 @@ namespace pacs_win_uia
BeginInvoke((Action)delegate
{
_liveTreeReadInFlight = false;
+ // 根窗口或读取代次已变,丢弃本次实时结果,避免覆盖更新的树。
if (IsDisposed || sequence != _inspectionSequence || handle != _treeRootHandle)
return;
if (error != null || task.IsCanceled || task.Result == null)
@@ -1842,6 +2051,7 @@ namespace pacs_win_uia
timer.Start();
}
+ // 应用一次完整树读取的结果:更新模型、重建树视图、刷新属性/监控与状态栏。
private void ApplyTree(ControlTreeResult result, NativeWindowInfo inspectedWindow, string label)
{
bool expandDeep = _expandPickedTree;
@@ -1939,6 +2149,7 @@ namespace pacs_win_uia
: ExplainIncomplete(node.ChildrenError);
}
+ // 深度优先找到第一个"具体"的不完整原因(跳过根占位的 DescendantIncomplete)。
private static string FindConcreteIncomplete(ControlTreeNode node)
{
if (node == null)
@@ -1964,6 +2175,7 @@ namespace pacs_win_uia
return null;
}
+ // 把不完整的错误码翻译成给操作者看的中文说明。
private static string ExplainIncomplete(string code)
{
switch (code)
@@ -1987,6 +2199,7 @@ namespace pacs_win_uia
}
}
+ // 树里是否含标题栏节点(用于判断"只读到窗口边框、没读到内容")。
private static bool ContainsTitleBar(ControlTreeNode node)
{
if (node == null)
@@ -2133,6 +2346,7 @@ namespace pacs_win_uia
ShowNodeMap();
}
+ // 用内存中的树矩形绘制所有控件框(不触发目标进程调用);无内容时自动关掉开关。
private void ShowNodeMap()
{
if (_currentTreeRoot == null || _treeRootHandle == IntPtr.Zero)
@@ -2166,6 +2380,7 @@ namespace pacs_win_uia
}
}
+ // 递归收集树中所有带有效矩形的节点(UIA/MSAA/Win32 三种矩形任取其一),跳过离屏与隐藏。
private static void CollectNodeBounds(ControlTreeNode node, IList target)
{
if (node == null)
@@ -2289,6 +2504,7 @@ namespace pacs_win_uia
if (changed) _propertyGrid.Refresh();
}
+ // 矩形值不同才写回;相同返回 false,避免无谓地触发属性网格重绘。
private static bool CopyRectangleIfDifferent(Func read, Action write, NativeRectangleInfo value)
{
NativeRectangleInfo old = read();
@@ -2303,6 +2519,7 @@ namespace pacs_win_uia
return true;
}
+ // 值不同才写回;相同返回 false,避免无谓地触发属性网格重绘。
private static bool CopyIfDifferent(Func read, Action write, T value)
{
T old = read();
@@ -2311,6 +2528,7 @@ namespace pacs_win_uia
return true;
}
+ // 按节点来源选出属性网格要展示的对象(UIA 元素 / MSAA 节点 / Win32 窗口)。
private static object SelectedObjectFor(ControlTreeNode node)
{
if (node == null)
@@ -2366,6 +2584,7 @@ namespace pacs_win_uia
ReconcileTreeView(true);
}
+ // 用协调器把模型差量同步到树视图:保留展开/选择状态,并就地刷新属性网格快照。
private void ReconcileTreeView(bool searchChanged)
{
TreeNode previousSelection = _controlTree.SelectedNode;
@@ -2388,6 +2607,7 @@ namespace pacs_win_uia
bool filter = _treeSearchPanel.OnlyMatches;
ControlTreeReconciler.Item root = BuildTreeItem(_currentTreeRoot, criteria, filter);
if (_treeReconciler == null) _treeReconciler = new ControlTreeReconciler(_controlTree);
+ // 重建期间置位 _restoringTreeState,抑制 AfterSelect 的副作用(清列表、改选中)。
_restoringTreeState = true;
try
{
@@ -2430,11 +2650,13 @@ namespace pacs_win_uia
}
}
+ // 判断搜索词是否为 XPath 查询(旧格式路径已停用,见 ControlPath.IsXPath)。
private static bool IsPathQuery(string text)
{
return ControlPath.IsXPath(text);
}
+ // 递归把模型节点转成协调器条目,按搜索条件标记命中/过滤(过滤时仍保留祖先链)。
private ControlTreeReconciler.Item BuildTreeItem(ControlTreeNode node, TreeSearchCriteria criteria, bool filter)
{
if (node == null) return null;
@@ -2493,6 +2715,7 @@ namespace pacs_win_uia
_controlTree.SelectedNode = target;
}
+ // 控件树选中变化:清空列表结果、把该节点同步到属性网格与监控编辑控件。
private void ControlTreeOnAfterSelect(object sender, TreeViewEventArgs e)
{
if (_restoringTreeState) return;
@@ -2524,6 +2747,7 @@ namespace pacs_win_uia
// ------------------------------------------------------------------ list read
+ // 读取当前选中控件的标准 UIA 列表模式;结果回到 UI 线程后应用。
private void ReadSelectedList()
{
if (_currentElement == null || !_currentElement.IsAvailable || _currentElement.Element == null)
@@ -2540,6 +2764,7 @@ namespace pacs_win_uia
return;
}
+ // 取消上一次列表读取(其序号随之作废)。
CancelListRead();
_listReadCancellation = CancellationTokenSource.CreateLinkedTokenSource(_shutdown.Token);
CancellationToken token = _listReadCancellation.Token;
@@ -2587,6 +2812,7 @@ namespace pacs_win_uia
{
Interlocked.Decrement(ref _activeReads);
stopwatch.Stop();
+ // 序号不匹配(已被取消或被新读取取代)时丢弃旧结果。
if (IsDisposed || !IsHandleCreated || sequence != _listReadSequence)
{
return;
@@ -2665,6 +2891,7 @@ namespace pacs_win_uia
|| (result.RowsRead <= 1 && result.ColumnCount <= 1);
}
+ // 打印被拾取元素及其上级/子元素的结构,用于判断 Provider 是否真的暴露了控件。
private void LogStructureDiagnostics(AutomationElement element, ListReadResult listResult)
{
try
@@ -2691,6 +2918,7 @@ namespace pacs_win_uia
}
}
+ // 取消并释放当前控件树读取的取消源(置空)。
private void CancelInspection()
{
if (_inspectionCancellation != null)
@@ -2701,6 +2929,7 @@ namespace pacs_win_uia
}
}
+ // 取消列表读取:自增序号(使旧回调作废)并释放取消源。
private void CancelListRead()
{
_listReadSequence++;
@@ -2712,6 +2941,7 @@ namespace pacs_win_uia
}
}
+ // 清空列表结果表格(先解绑数据源再清表结构)。
private void ClearListResultGrid()
{
if (_listResultTable != null)
@@ -2726,6 +2956,7 @@ namespace pacs_win_uia
}
}
+ // 把列表读取结果转成 DataTable(列名去重、越界单元格回退为"[不可用]")。
private DataTable BuildListGridTable(ListReadResult result)
{
var table = new DataTable();
@@ -2778,6 +3009,7 @@ namespace pacs_win_uia
return table;
}
+ // 应用列表读取结果:更新状态栏、底部提示标签与表格数据源。
private void ApplyListResult(ListReadResult result)
{
if (result == null)
@@ -2867,6 +3099,7 @@ namespace pacs_win_uia
return builder.ToString();
}
+ // 导出最近一次列表结果(先弹敏感数据确认,再选 JSON/CSV 保存)。
private void ExportLastListResult()
{
if (_lastListResult == null)
@@ -2923,6 +3156,7 @@ namespace pacs_win_uia
}
}
+ // 把当前控件树导出为 JSON。
private void ExportCurrentTree()
{
if (_currentTreeRoot == null)
@@ -2955,6 +3189,7 @@ namespace pacs_win_uia
}
}
+ // 取窗口列表当前选中项对应的窗口(未选中返回 null)。
private NativeWindowInfo GetSelectedWindow()
{
return _windowList.SelectedItems.Count == 0
@@ -3084,6 +3319,7 @@ namespace pacs_win_uia
};
}
+ // 取节点在屏幕上的矩形(UIA / MSAA / Win32 任一有效者优先)。
private static Rectangle? BoundsOfNode(ControlTreeNode node)
{
NativeRectangleInfo bounds = null;
@@ -3165,6 +3401,7 @@ namespace pacs_win_uia
return;
}
+ // 不退回子树、不保存猜测路径:宁可不选中,也不给出错误身份,以免操作者定位到别的控件。
_autoAddPendingPick = false;
SetStatus("当前窗口树中没有拾取到的节点(控件已变化或读取被截断)。不会改用另一棵子树或保存猜测路径;请提高读取限制后重试。", null);
}
@@ -3202,6 +3439,7 @@ namespace pacs_win_uia
return true;
}
+ // 隐藏定位框并清空定位记录;reason 非空时写入状态栏。
private void HideLocateFrame(string reason)
{
_locateFollower.Hide(reason);
@@ -3244,6 +3482,7 @@ namespace pacs_win_uia
return true;
}
+ // 在树视图里深度优先查找与目标模型"同一控件"的节点。
private static TreeNode FindTreeNode(TreeNodeCollection nodes, ControlTreeNode target)
{
foreach (TreeNode node in nodes)
@@ -3304,6 +3543,7 @@ namespace pacs_win_uia
_propertyGrid.Refresh();
}
+ // 监控编辑控件的状态消息透传到状态栏。
private void MonitorEditorOnStatusChanged(object sender, ControlMonitorStatusEventArgs e)
{
SetStatus(e.Message, e.Exception);
@@ -3338,6 +3578,7 @@ namespace pacs_win_uia
SetStatus(inTree ? "已跳到控件树搜索框。" : "已跳到窗口列表搜索框(Ctrl+F 在控件树页时跳到控件树搜索)。", null);
}
+ // 判断控件是否位于某祖先控件内(用于 Ctrl+F 判断当前上下文)。
private static bool IsWithin(Control ancestor, Control control)
{
for (Control current = control; current != null; current = current.Parent)
@@ -3351,6 +3592,7 @@ namespace pacs_win_uia
return false;
}
+ // 写状态栏(带时间戳);有异常时同时记日志。
private void SetStatus(string message, Exception exception)
{
string detail = exception == null ? string.Empty : Environment.NewLine + exception.GetType().Name + ": " + exception.Message;
@@ -3361,6 +3603,7 @@ namespace pacs_win_uia
}
}
+ // 关闭前:有未保存监控改动先确认,再保存设置、跑退出钩子、停定时器并释放资源。
private void MainFormOnFormClosing(object sender, FormClosingEventArgs e)
{
if (_monitorEditor.HasUnsavedChanges)
@@ -3398,6 +3641,7 @@ namespace pacs_win_uia
_treeReadTimer.Stop();
_treeReadTimer.Tick -= TreeReadTimerOnTick;
_treeReadTimer.Dispose();
+ // 自增两个序号并取消,确保关闭后仍回来的后台回调不会更新已销毁的界面。
_inspectionSequence++;
_listReadSequence++;
CancelInspection();
diff --git a/src/pacs_win_uia/UI/NodeMapOverlayForm.cs b/src/pacs_win_uia/UI/NodeMapOverlayForm.cs
index 7849042..db1ca92 100644
--- a/src/pacs_win_uia/UI/NodeMapOverlayForm.cs
+++ b/src/pacs_win_uia/UI/NodeMapOverlayForm.cs
@@ -1,3 +1,31 @@
+// ============================================================================
+// NodeMapOverlayForm —— 控件“节点地图”覆盖层(诊断/运行时两层模式)
+//
+// 职责:
+// 把一棵 UI 树里每个节点的屏幕矩形画成红框叠在目标窗口上;在“选取模式”下让操作者用鼠标点框
+// 取到该节点的 path。只轮询窗口几何,从不做 UIA。
+//
+// 两层模式:
+// · 诊断层:NodeMapActionsForm(“点击框获取path/退出绘制”小面板)配合选取模式,供开发/排障。
+// · 运行时层:正常透明覆盖、只画框、点击穿透;目标最小化/切走时挂起重绘但不丢快照。
+//
+// 被谁调用:
+// MainForm 在每次树刷新后调用 ShowMap/SetItems(UI 线程);选中节点通过 NodeSelected/NodePicked 回传。
+//
+// 节拍与线程:
+// · UI 线程:300ms 定时器 RefreshMap 只重算几何与遮挡(用 WindowVisibility),不遍历树、不读 UIA。
+// · 只有选取模式才安装 WH_MOUSE_LL / WH_KEYBOARD_LL 低级钩子,退出即卸载。
+//
+// 不抢焦点/点击穿透:CreateParams 设 WS_EX_TOOLWINDOW|WS_EX_NOACTIVATE|WS_EX_TRANSPARENT;
+// WM_NCHITTEST 返回 HTTRANSPARENT;WM_MOUSEACTIVATE 返回 MA_NOACTIVATE。
+//
+// 跟随锚点 + 相对偏移 / 最小化遮挡时隐藏:
+// 框坐标以锚定顶层窗口左上角为原点存成相对偏移(Entry.Offset);RefreshMap 时若目标不可见/
+// 被完全遮挡/非前台,就隐藏表面(HideSurfaces)并退出选取模式,目标恢复后自动复现。
+//
+// “要改什么就改哪里”:快照/几何 → ReplaceItems / RefreshMap;选取与钩子 → SetSelectionMode /
+// MouseHookCallback / KeyboardHookCallback;绘制 → OnPaint。
+// ============================================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -11,6 +39,7 @@ using pacs_win_uia.Services;
namespace pacs_win_uia.UI
{
/// An immutable tree-refresh snapshot; Bounds are screen coordinates, Node is caller-owned.
+ /// 一次树刷新后的不可变快照:屏幕矩形 + 调用方拥有的节点对象;供覆盖层只读使用。
public class NodeMapItem
{
public NodeMapItem(Rectangle bounds, object node = null, string path = null)
@@ -19,12 +48,16 @@ namespace pacs_win_uia.UI
Node = node;
Path = path;
}
+ /// 节点屏幕矩形。
public Rectangle Bounds { get; private set; }
+ /// 调用方提供的节点对象(本类不改动)。
public object Node { get; private set; }
+ /// 节点的 XPath/定位路径。
public string Path { get; private set; }
}
/// Preferred integration name: one node, its path, and its screen rectangle.
+ /// 首选的集成类型:一个节点、它的 path 与屏幕矩形(NodeMapItem 的别名派生)。
public sealed class NodeMapEntry : NodeMapItem
{
public NodeMapEntry(Rectangle bounds, object node = null, string path = null)
@@ -34,6 +67,7 @@ namespace pacs_win_uia.UI
: base(bounds, node, path) { }
}
+ /// 节点被选中(点框/滚轮确认)时的事件参数。
public sealed class NodeMapSelectionEventArgs : EventArgs
{
internal NodeMapSelectionEventArgs(int index, NodeMapItem item, Point point)
@@ -43,10 +77,15 @@ namespace pacs_win_uia.UI
ScreenPoint = point;
}
/// Index in the supplied list, including any skipped null/empty items.
+ /// 在传入列表中的索引(包含被跳过的 null/空项)。
public int Index { get; private set; }
+ /// 被选中的快照项。
public NodeMapItem Item { get; private set; }
+ /// 被选中项的节点对象。
public object Node { get { return Item.Node; } }
+ /// 被选中项的 path。
public string Path { get { return Item.Path; } }
+ /// 触发选中时的鼠标屏幕坐标。
public Point ScreenPoint { get; private set; }
}
@@ -55,30 +94,50 @@ namespace pacs_win_uia.UI
/// refresh; only window geometry is polled here, never UIA. Minimizing/backgrounding suspends
/// rendering without losing the snapshot. Closing the target ends the map.
///
+ /// 点击穿透、非激活的节点地图覆盖层;每次树刷新后在 UI 线程调用 ShowMapItems/SetItems。
public sealed class NodeMapOverlayForm : Form
{
+ /// 一个待绘制条目的相对偏移与来源。
private sealed class Entry
{
+ /// 在传入列表中的原始索引(事件回传用)。
internal int Index;
+ /// 来源快照项。
internal NodeMapItem Item;
+ /// 相对锚定窗口左上角的偏移矩形(跟随窗口移动)。
internal Rectangle Offset;
}
+ /// UI 线程 300ms 刷新定时器。
private readonly Timer _timer;
+ /// 旁边的“选取/退出”小面板。
private readonly NodeMapActionsForm _actions;
+ /// 当前快照条目(已转成相对锚定窗口左上角的偏移)。
private readonly List _entries = new List();
+ /// 当前鼠标位置命中的候选(重叠时可能多个),供滚轮切换。
private readonly List _candidates = new List();
+ /// 低级鼠标钩子回调委托(必须持有引用,否则可能被 GC 回收)。
private readonly NativeMethods.LowLevelMouseProc _mouseProc;
+ /// 低级键盘钩子回调委托(同上,必须持有引用)。
private readonly NativeMethods.LowLevelKeyboardProc _keyboardProc;
+ /// 已安装的鼠标/键盘钩子句柄,以及锚定顶层窗口句柄。
private IntPtr _mouseHook, _keyboardHook, _anchor;
+ /// 锚定窗口最近一次的屏幕矩形。
private Rectangle _anchorBounds;
+ /// _shown=期望显示;_selectionMode=处于选取模式;_disposing=正在释放;_escapeSuppressed=已吞 Esc 按下。
private bool _shown, _selectionMode, _disposing, _escapeSuppressed;
+ /// _suppressedButtons=已吞掉的鼠标按键位掩码;_candidateIndex=当前候选;_version=快照版本号。
private int _suppressedButtons, _candidateIndex, _version;
+ /// 选取模式下按下的命中项。
private Entry _pressedEntry;
+ /// 按下时的快照版本号(版本变化则丢弃本次选取)。
private int _pressedVersion;
+ /// 上次计算候选时的鼠标屏幕点。
private Point _candidatePoint;
+ /// 是否已有 _candidatePoint(用于“同点同候选”判断)。
private bool _hasCandidatePoint;
+ /// 初始化窗体样式、创建刷新定时器与动作面板,并接线面板的选取/退出事件。
public NodeMapOverlayForm()
{
FormBorderStyle = FormBorderStyle.None;
@@ -103,20 +162,28 @@ namespace pacs_win_uia.UI
};
}
+ /// 节点被选中时触发。
public event EventHandler NodeSelected;
/// Preferred event name for MainForm integration; aliases NodeSelected.
+ /// MainForm 集成偏好的事件名;等价于 NodeSelected。
public event EventHandler NodePicked
{
add { NodeSelected += value; }
remove { NodeSelected -= value; }
}
+ /// 选取模式切换时触发。
public event EventHandler SelectionModeChanged;
+ /// 地图退出(目标关闭或面板退出)时触发。
public event EventHandler MapExited;
/// Requested map state (also true while temporarily hidden). Visible is actual visibility.
+ /// 期望的地图状态(暂时隐藏时仍为 true);实际可见性看 Visible。
public bool IsShown { get { return _shown; } }
+ /// 是否处于选取模式。
public bool IsSelectionMode { get { return _selectionMode; } }
+ /// 当前快照里的框数量。
public int RectangleCount { get { return _entries.Count; } }
+ /// 几何刷新周期(毫秒,最小 1)。
public int RefreshIntervalMs
{
get { return _timer.Interval; }
@@ -127,7 +194,9 @@ namespace pacs_win_uia.UI
}
}
+ /// 显示时不激活窗口。
protected override bool ShowWithoutActivation { get { return true; } }
+ /// 扩展样式:工具窗口、不激活、鼠标穿透。
protected override CreateParams CreateParams
{
get
@@ -138,6 +207,7 @@ namespace pacs_win_uia.UI
return parameters;
}
}
+ /// 让点击穿透(HTTRANSPARENT)并拒绝激活(MA_NOACTIVATE)。
protected override void WndProc(ref Message message)
{
if (message.Msg == NativeMethods.WM_NCHITTEST)
@@ -154,6 +224,7 @@ namespace pacs_win_uia.UI
}
/// Legacy API. Selection events still return the original rectangle-list index.
+ /// 旧接口:只给矩形列表;选中事件仍返回原始矩形列表索引。
public void ShowMap(IntPtr anchorWindow, IList screenRectangles)
{
List items = null;
@@ -166,6 +237,7 @@ namespace pacs_win_uia.UI
}
/// Preferred entry API. NodeMapEntry derives from NodeMapItem.
+ /// 首选接口:传入 NodeMapEntry(派生于 NodeMapItem)。
public void ShowMap(IntPtr anchorWindow, IList entries)
{
if (entries == null)
@@ -179,6 +251,7 @@ namespace pacs_win_uia.UI
}
/// Starts/replaces the map, but never shows it until the target is foreground and visible.
+ /// 开始/替换地图;只在目标前台且可见时才真正显示(否则等价隐藏)。
public void ShowMapItems(IntPtr anchorWindow, IList items)
{
if (IsDisposed) throw new ObjectDisposedException(GetType().Name);
@@ -202,6 +275,7 @@ namespace pacs_win_uia.UI
/// Supplies a new screen-coordinate snapshot without starting a stopped map. Empty lists keep
/// the map session alive, so a later tree refresh can restore its frames. UI thread only.
///
+ /// 更新快照(屏幕坐标)但不启动已停止的地图;空列表也保活会话,仅 UI 线程调用。
public void SetItems(IList items)
{
Rectangle bounds;
@@ -210,6 +284,7 @@ namespace pacs_win_uia.UI
RefreshMap();
}
+ /// 替换快照:递增版本号、把屏幕坐标转成相对锚定窗口的偏移,并清空候选。
private void ReplaceItems(IList items, Rectangle bounds)
{
_version++;
@@ -229,6 +304,7 @@ namespace pacs_win_uia.UI
ClearCandidates();
}
+ /// 结束地图会话:清空快照、退出选取模式、隐藏所有表面并停表。
public void HideMap()
{
_shown = false;
@@ -241,6 +317,7 @@ namespace pacs_win_uia.UI
}
/// Enables hooks only while selecting. On failure, leaves normal click-through mode.
+ /// 开关选取模式:进入时装低级钩子(失败回退普通穿透模式),退出时卸载钩子。
public void SetSelectionMode(bool enabled)
{
enabled = enabled && _shown && Visible && WindowVisibility.IsForegroundWindow(_anchor);
@@ -269,9 +346,11 @@ namespace pacs_win_uia.UI
if (handler != null && !_disposing) handler(this, EventArgs.Empty);
}
+ /// 300ms 定时器回调,转发到 RefreshMap。
private void OnTimerTick(object sender, EventArgs e) { RefreshMap(); }
/// Immediately recomputes geometry/occlusion. No tree traversal or UIA reads.
+ /// 立即重算几何与遮挡:目标不可见/非前台就隐藏表面并退出选取;不做树遍历或 UIA。
public void RefreshMap()
{
if (!_shown || _disposing) return;
@@ -319,6 +398,7 @@ namespace pacs_win_uia.UI
}
}
+ /// 设置窗体 Region 并释放上一个(形状变化时用)。
private void ReplaceRegion(Region region)
{
Region previous = Region;
@@ -326,6 +406,7 @@ namespace pacs_win_uia.UI
if (previous != null && !ReferenceEquals(previous, region)) previous.Dispose();
}
+ /// 隐藏覆盖层与动作面板,清掉 Region 与候选。
private void HideSurfaces()
{
Hide();
@@ -334,6 +415,7 @@ namespace pacs_win_uia.UI
ClearCandidates();
}
+ /// 该点此刻是否应由本覆盖层拦截(选取模式、可见、前台、非动作面板,且在实时可见区域内)。
private bool CanIntercept(Point point)
{
if (!_selectionMode || !Visible || !WindowVisibility.IsForegroundWindow(_anchor) ||
@@ -346,6 +428,7 @@ namespace pacs_win_uia.UI
using (visible) return visible.IsVisible(point);
}
+ /// 清空候选并复位索引,同步清掉动作面板的候选显示。
private void ClearCandidates()
{
_candidates.Clear();
@@ -354,6 +437,7 @@ namespace pacs_win_uia.UI
_actions.SetCandidate(0, 0, null);
}
+ /// 按鼠标点重算候选(重叠时按面积从小到大排序),cycle=true 时用滚轮方向切换当前候选。
private void UpdateCandidates(Point point, bool cycle, int direction = 1)
{
Rectangle bounds;
@@ -383,11 +467,13 @@ namespace pacs_win_uia.UI
Invalidate();
}
+ /// 当前候选(无候选时返回 null)。
private Entry CurrentCandidate
{
get { return _candidates.Count == 0 ? null : _candidates[_candidateIndex]; }
}
+ /// 把鼠标消息映射成按键位掩码(左1/右2/中4/X1=8/X2=16),并输出按下/抬起标志。
private static int ButtonMask(int message, uint data, out bool down, out bool up)
{
down = message == NativeMethods.WM_LBUTTONDOWN || message == NativeMethods.WM_RBUTTONDOWN ||
@@ -401,6 +487,7 @@ namespace pacs_win_uia.UI
return (data >> 16) == 1 ? 8 : 16;
}
+ /// 低级鼠标钩子:选取模式下吞掉目标可见区域内的点击/滚轮,并把抬起配对到按下的候选(版本一致才派发)。
private IntPtr MouseHookCallback(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0) return NativeMethods.CallNextHookEx(_mouseHook, code, wParam, lParam);
@@ -466,6 +553,7 @@ namespace pacs_win_uia.UI
return NativeMethods.CallNextHookEx(_mouseHook, code, wParam, lParam);
}
+ /// 低级键盘钩子:吞掉 Esc(抬起时退出选取模式),避免它漏给被检查的窗口。
private IntPtr KeyboardHookCallback(int code, IntPtr wParam, IntPtr lParam)
{
if (code >= 0)
@@ -487,6 +575,7 @@ namespace pacs_win_uia.UI
return NativeMethods.CallNextHookEx(_keyboardHook, code, wParam, lParam);
}
+ /// 安全地把动作抛回 UI 线程(句柄已销毁/正在释放时静默忽略)。
private void Post(Action action)
{
if (_disposing || IsDisposed || !IsHandleCreated) return;
@@ -494,6 +583,7 @@ namespace pacs_win_uia.UI
catch (InvalidOperationException) { }
}
+ /// 卸载钩子;非 force 时会等到已吞的按键/ Esc 抬起后再卸,避免漏掉配对的抬起。
private void ReleaseHooks(bool force)
{
if (_mouseHook != IntPtr.Zero && (force || _suppressedButtons == 0))
@@ -509,6 +599,7 @@ namespace pacs_win_uia.UI
if (force) { _suppressedButtons = 0; _escapeSuppressed = false; }
}
+ /// 把红框画进可见区域(用 Region 裁剪);选取模式下高亮当前候选。
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
@@ -522,6 +613,7 @@ namespace pacs_win_uia.UI
using (var pen = new Pen(Color.DodgerBlue, 3F)) e.Graphics.DrawRectangle(pen, selected.Offset);
}
+ /// 取窗口屏幕矩形;句柄无效、调用失败或零尺寸返回 false。
private static bool TryGetWindowRectangle(IntPtr window, out Rectangle rectangle)
{
NativeMethods.RECT native;
@@ -531,6 +623,7 @@ namespace pacs_win_uia.UI
return rectangle.Width > 0 && rectangle.Height > 0;
}
+ /// 释放:卸载钩子、停表、销毁动作面板、清 Region/快照并解绑所有事件。
protected override void Dispose(bool disposing)
{
if (disposing && !_disposing)
@@ -555,13 +648,19 @@ namespace pacs_win_uia.UI
}
// Kept in the already compiled overlay source so integration requires no csproj changes.
+ /// 地图旁的小操作面板:切换选取模式、退出绘制、显示当前候选。
internal sealed class NodeMapActionsForm : Form
{
+ /// “点击框获取path / 选取中”按钮。
private readonly Button _select;
+ /// 候选信息标签(候选 i/n 与 path)。
private readonly Label _candidate;
+ /// 请求切换选取模式。
internal event EventHandler ToggleSelection;
+ /// 请求退出地图。
internal event EventHandler ExitMap;
+ /// 构建面板控件并接线按钮点击(选取切换失败时在标签上提示)。
internal NodeMapActionsForm()
{
FormBorderStyle = FormBorderStyle.None;
@@ -588,7 +687,9 @@ namespace pacs_win_uia.UI
Controls.Add(exit);
Controls.Add(_candidate);
}
+ /// 显示时不激活窗口(面板可被点击但不抢键盘焦点)。
protected override bool ShowWithoutActivation { get { return true; } }
+ /// 扩展样式:工具窗口、不激活(但可接收鼠标点击)。
protected override CreateParams CreateParams
{
get
@@ -598,6 +699,7 @@ namespace pacs_win_uia.UI
return parameters;
}
}
+ /// 拒绝激活(MA_NOACTIVATE),点击面板不抢目标窗口焦点。
protected override void WndProc(ref Message message)
{
if (message.Msg == NativeMethods.WM_MOUSEACTIVATE)
@@ -607,6 +709,7 @@ namespace pacs_win_uia.UI
}
base.WndProc(ref message);
}
+ /// 把面板贴到目标窗口右侧(放不下则改左侧,并夹在工作区内)。
internal void PositionBeside(Rectangle target)
{
Rectangle area = Screen.FromRectangle(target).WorkingArea;
@@ -617,11 +720,13 @@ namespace pacs_win_uia.UI
int y = Math.Max(area.Top, Math.Min(target.Top + 8, area.Bottom - Height));
Location = new Point(x, y);
}
+ /// 按选取模式更新按钮文案与配色。
internal void SetSelectionMode(bool enabled)
{
_select.Text = enabled ? "选取中(Esc退出)" : "点击框获取path";
_select.BackColor = enabled ? Color.LightSkyBlue : SystemColors.Control;
}
+ /// 刷新候选标签(i/n + path;无候选时显示操作提示)。
internal void SetCandidate(int index, int count, string path)
{
string text = count == 0 ? "选取后滚轮切换重叠节点" :
diff --git a/src/pacs_win_uia/UI/PathLocateForm.cs b/src/pacs_win_uia/UI/PathLocateForm.cs
index 1aed47b..2a7efe4 100644
--- a/src/pacs_win_uia/UI/PathLocateForm.cs
+++ b/src/pacs_win_uia/UI/PathLocateForm.cs
@@ -3,6 +3,21 @@ using System.Drawing;
using System.Windows.Forms;
using pacs_win_uia.Models;
+/*
+ * PathLocateForm —— “按 path 定位”对话框。
+ * 职责:粘贴一段控件 XPath 并校验它能否唯一定位。这里接受的路径文本与工具各处打印的完全一致
+ * (控件树 / PropertyGrid 的控件Path / 监控列表的控件Path),因此从任意位置复制回来都能复核。
+ * 被谁调用:MainForm 的“杂项 → 按 path 定位…”(LocateByPath)以 ShowDialog 打开,读 PathText。
+ * 交互清单:
+ * - 顶部说明标签 + 只读 XPath 帮助文本(来自 ControlPathEditorForm.XPathHelp)。
+ * - 中部多行文本框供粘贴路径;文本变化时清空错误提示。
+ * - 底部按钮:定位(校验通过则置 DialogResult.OK 并关闭)、取消(Cancel)、清空。
+ * - 回车 = 定位,Esc = 取消。
+ * 要改什么就改哪里:
+ * - 校验规则:ControlMonitorRules.ValidateControlPath(仅接受 XPath,拒绝旧格式,须唯一匹配)。
+ * - 帮助文本:ControlPathEditorForm.XPathHelp。
+ */
+
namespace pacs_win_uia.UI
{
///
@@ -12,8 +27,10 @@ namespace pacs_win_uia.UI
///
public sealed class PathLocateForm : Form
{
+ // 粘贴路径的输入框。
private readonly TextBox _path;
+ // 构造函数:initialPath 为预填路径;windowDescription 为“定位窗口”的说明(为空时提示先选窗口/拾取控件)。
public PathLocateForm(string initialPath, string windowDescription)
{
Text = "按 path 定位";
@@ -70,6 +87,7 @@ namespace pacs_win_uia.UI
};
var cancel = new Button { Text = "取消", AutoSize = true, DialogResult = DialogResult.Cancel };
var locate = new Button { Text = "定位", AutoSize = true };
+ // 定位:先校验路径;通过则返回 OK 并关闭,否则在底部显示错误。
locate.Click += delegate
{
string error = ControlMonitorRules.ValidateControlPath(_path.Text);
@@ -78,6 +96,7 @@ namespace pacs_win_uia.UI
DialogResult = DialogResult.OK;
Close();
};
+ // 编辑路径时清除旧的错误提示。
_path.TextChanged += delegate { errorLabel.Text = string.Empty; };
var clear = new Button { Text = "清空", AutoSize = true };
clear.Click += delegate { _path.Text = string.Empty; };
@@ -95,6 +114,7 @@ namespace pacs_win_uia.UI
}
/// The pasted path text.
+ // 粘贴的路径文本;对话框以 OK 关闭后由调用方读取。
public string PathText
{
get { return _path.Text; }
diff --git a/src/pacs_win_uia/UI/PickerOverlayForm.cs b/src/pacs_win_uia/UI/PickerOverlayForm.cs
index 52316f1..43cef5e 100644
--- a/src/pacs_win_uia/UI/PickerOverlayForm.cs
+++ b/src/pacs_win_uia/UI/PickerOverlayForm.cs
@@ -3,17 +3,38 @@ using System.Drawing;
using System.Windows.Forms;
using pacs_win_uia.Interop;
+// ============================================================================
+// PickerOverlayForm.cs —— 十字拾取的虚拟屏覆盖层窗体
+// 职责:铺满整个虚拟屏幕的透明覆盖层,接管确认点击(不激活),周期性报告光标位置与光标下的原生窗口
+// 句柄,供 CrosshairPicker 决策。
+// 点击穿透与不抢焦点:ShowWithoutActivation + WS_EX_TOOLWINDOW/WS_EX_NOACTIVATE;构造函数用
+// BackColor=TransparencyKey=Magenta 让整面窗体视觉透明(透明区域点击会落到下层窗口,便于看到光标
+// 下的真实窗口)。WndProc 里 WM_NCHITTEST 返回 HTCLIENT、WM_MOUSEACTIVATE 返回 MA_NOACTIVATE。
+// 注意:真正保证“不触发目标控件”的是 CrosshairPicker 装的低级鼠标钩子(吞掉左键),本窗体自身的
+// 鼠标事件只在确实收到点击时起作用。
+// 解析底层窗口:ResolveUnderlyingWindow 会短暂隐藏覆盖层再 WindowFromPoint,避免查到自己。
+// Esc 取消:定时器轮询 GetAsyncKeyState(VK_ESCAPE)。
+// 被谁调用:由 CrosshairPicker.Start 创建并 Show。
+// 要改什么就改哪里:
+// - 透明/穿透/不激活:构造函数的 TransparencyKey 与 CreateParams/WndProc。
+// - 光标位置与点击检测:TimerOnTick(含 _inputArmed 对工具栏按钮抬起事件的规避)。
+// - 底层窗口解析:ResolveUnderlyingWindow。
+// ============================================================================
namespace pacs_win_uia.UI
{
+ // 光标位置事件参数:屏幕坐标 + 该点下的原生窗口句柄。
public sealed class CursorPositionEventArgs : EventArgs
{
+ // 构造:记录坐标与句柄。
public CursorPositionEventArgs(Point screenPoint, IntPtr windowHandle)
{
ScreenPoint = screenPoint;
WindowHandle = windowHandle;
}
+ // 光标屏幕坐标。
public Point ScreenPoint { get; private set; }
+ // 光标下的原生窗口句柄。
public IntPtr WindowHandle { get; private set; }
}
@@ -21,19 +42,30 @@ namespace pacs_win_uia.UI
/// Virtual-screen picker overlay. It captures the confirmation click without
/// activating, and briefly hides itself only while resolving the underlying HWND.
///
+ /// 虚拟屏覆盖层:不激活地接管确认点击,仅在解析底层 HWND 时短暂隐藏自己。
public sealed class PickerOverlayForm : Form
{
+ // 轮询定时器(光标位置 / Esc / 左键状态)。
private readonly Timer _timer;
+ // 上一次观察到的左键是否按下。
private bool _leftButtonWasDown;
+ // 是否已武装输入:避免把释放工具栏按钮那一下当成拾取。
private bool _inputArmed;
+ // 最近一次光标屏幕坐标。
private Point _lastCursorPosition;
+ // 是否已有 _lastCursorPosition。
private bool _hasCursorPosition;
+ // 记录覆盖层的原生可见状态(解析底层窗口时临时隐藏)。
private bool _overlayNativeVisible;
+ // 光标移动事件。
public event EventHandler CursorMoved;
+ // 按下 Esc 事件。
public event EventHandler EscapePressed;
+ // 左键释放(确认拾取)事件。
public event EventHandler LeftButtonReleased;
+ // 构造:设无边框、置顶、整虚拟屏透明、十字光标,并建 40ms 定时器。
public PickerOverlayForm()
{
FormBorderStyle = FormBorderStyle.None;
@@ -49,13 +81,16 @@ namespace pacs_win_uia.UI
_timer.Tick += TimerOnTick;
}
+ // 最近一次光标屏幕坐标(只读)。
public Point CurrentScreenPoint
{
get { return _lastCursorPosition; }
}
+ // 最近一次光标下的原生窗口句柄(只读)。
public IntPtr CurrentWindowHandle { get; private set; }
+ // 按给定坐标刷新并返回底层窗口句柄(点击确认时用)。
public IntPtr RefreshCurrentWindowHandle(Point screenPoint)
{
_lastCursorPosition = screenPoint;
@@ -64,11 +99,13 @@ namespace pacs_win_uia.UI
return CurrentWindowHandle;
}
+ // 显示时不激活(不抢目标窗口焦点)。
protected override bool ShowWithoutActivation
{
get { return true; }
}
+ // 扩展样式:工具窗口 + 不激活,避免出现在任务栏/抢焦点。
protected override CreateParams CreateParams
{
get
@@ -80,6 +117,7 @@ namespace pacs_win_uia.UI
}
}
+ // 窗口消息钩子:命中测试返回 HTCLIENT 以接收确认点击;鼠标激活请求返回 MA_NOACTIVATE 以不激活。
protected override void WndProc(ref Message message)
{
if (message.Msg == NativeMethods.WM_NCHITTEST)
@@ -98,6 +136,7 @@ namespace pacs_win_uia.UI
base.WndProc(ref message);
}
+ // 鼠标按下:仅在输入已武装时记录左键按下。
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
@@ -107,6 +146,7 @@ namespace pacs_win_uia.UI
}
}
+ // 鼠标抬起:若之前记录过左键按下,则抛出 LeftButtonReleased。
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
@@ -121,6 +161,7 @@ namespace pacs_win_uia.UI
}
}
+ // 定时器:检测 Esc、光标移动(上报 CursorMoved)、左键释放(确认拾取),并处理输入武装。
private void TimerOnTick(object sender, EventArgs e)
{
if ((NativeMethods.GetAsyncKeyState(NativeMethods.VK_ESCAPE) & 0x8000) != 0)
@@ -174,6 +215,7 @@ namespace pacs_win_uia.UI
_leftButtonWasDown = leftButtonDown;
}
+ // 解析屏幕点下的底层窗口:先隐藏覆盖层(否则会查到自己),查完再恢复显示。
private IntPtr ResolveUnderlyingWindow(Point screenPoint)
{
bool wasVisible = _overlayNativeVisible;
@@ -197,6 +239,7 @@ namespace pacs_win_uia.UI
}
}
+ // 显示后:以不激活方式再现,取初始光标位置并上报一次,随后武装输入并启动定时器。
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
@@ -220,6 +263,7 @@ namespace pacs_win_uia.UI
_timer.Start();
}
+ // 释放:停并销毁定时器,清空事件订阅。
protected override void Dispose(bool disposing)
{
if (disposing)
diff --git a/src/pacs_win_uia/UI/ScrollHostPanel.cs b/src/pacs_win_uia/UI/ScrollHostPanel.cs
index 795936f..93802e4 100644
--- a/src/pacs_win_uia/UI/ScrollHostPanel.cs
+++ b/src/pacs_win_uia/UI/ScrollHostPanel.cs
@@ -1,6 +1,19 @@
using System;
using System.Windows.Forms;
+/*
+ * ScrollHostPanel —— 可横向滚动的宿主面板(属性区 / 长内容区)。
+ * 职责:把单个内容控件放进带 AutoScroll 的面板,并保证内容宽度至少为 MinimumContentWidth;
+ * 窄屏时底部出现横向滚动条,内容右侧不会被裁掉(只支持 AutoScroll 的控件在子控件比视口
+ * 窄时并不会出现滚动条,所以这里强制了最小宽度)。
+ * 被谁调用:MainForm 的属性区 host(new ScrollHostPanel { Dock = Fill, MinimumContentWidth = 360 }),
+ * 把 PropertyGrid 等赋给 Content。
+ * 交互清单:拖动底部横向滚动条 → 查看被裁掉的右半部分内容。
+ * 要改什么就改哪里:
+ * - 内容最小宽度(默认 460):MinimumContentWidth。
+ * - 内容跟随面板尺寸的方式:LayoutContent。
+ */
+
namespace pacs_win_uia.UI
{
///
@@ -11,17 +24,22 @@ namespace pacs_win_uia.UI
///
public sealed class ScrollHostPanel : Panel
{
+ // 被托管的单个内容控件;由 Content 属性设置。
private Control _content;
+ // 防止 LayoutContent 在 SetBounds 触发的重入布局中递归。
private bool _layingOut;
+ // 构造函数:开启自动滚动并设置默认最小内容宽度 460。
public ScrollHostPanel()
{
AutoScroll = true;
MinimumContentWidth = 460;
}
+ // 内容控件的最小宽度;低于它会触发横向滚动条(默认 460)。
public int MinimumContentWidth { get; set; }
+ // 被托管的内容控件:赋新值时从旧内容移除、把新内容 Dock 设为 None 后加入并重新布局。
public Control Content
{
get { return _content; }
@@ -48,18 +66,21 @@ namespace pacs_win_uia.UI
}
}
+ // 布局变化时重新摆放内容控件。
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
LayoutContent();
}
+ // 客户区尺寸变化(含滚动条出现/消失)时重新摆放内容控件。
protected override void OnClientSizeChanged(EventArgs e)
{
base.OnClientSizeChanged(e);
LayoutContent();
}
+ // 把内容控件铺满客户区,宽度不小于 MinimumContentWidth;用 _layingOut 防止 SetBounds 触发的递归布局。
private void LayoutContent()
{
if (_content == null || _layingOut)
diff --git a/src/pacs_win_uia/UI/SettingsForm.cs b/src/pacs_win_uia/UI/SettingsForm.cs
index 9b7015f..98a851a 100644
--- a/src/pacs_win_uia/UI/SettingsForm.cs
+++ b/src/pacs_win_uia/UI/SettingsForm.cs
@@ -1,4 +1,28 @@
-using System;
+// ============================================================================
+// SettingsForm.cs —— 设置对话框(所有可配置项的编辑入口)
+// 职责:把 AppSettings 的每一项做成可编辑界面;编辑的是【副本/草稿】,只有点「保存」且校验
+// 通过才写盘,取消则整体丢弃(见 Save / CopyBars / CopyTriggers)。
+// 被谁调用:MainForm.ShowSettings() 打开;保存成功后通过 Result 属性把 _settings 交回 MainForm,
+// 由 MainForm 负责让新设置生效。
+// 页面结构(TabControl,每页对应一组字段):
+// · 关于 BuildAboutPage —— 只读能力/路径说明文本,无字段。
+// · 界面 BuildUiPage —— _autoReadTree/_highlightForeground/_treeDepth/_treeNodes/
+// _treeTimeout/_treeRefreshInterval/_readTimeout/_skipDisabled
+// → 存回 _settings.Ui.* 与 _settings.Read.*。
+// · 悬浮按钮 BuildFloatingPage —— 悬浮条列表 _barList、按钮网格 _buttonGrid、
+// 窗口条件三件套 _barProcess/_barClass/_barTitle 等
+// → 存回 _settings.FloatingButton.Bars 与 RefreshIntervalMs。
+// · 命令 BuildCommandPage —— _triggerList(执行时机)与 _commandGrid(命令)
+// → 存回 _settings.Commands.Triggers。
+// · OCR BuildOcrPage —— _ocrEnabled/_ocrBaseUrl/_ocrConfidence/_ocrTimeout/
+// _ocrSaveScreenshots/_ocrDirectory → 存回 _settings.Ocr.*。
+// 保存流程(Save):EndEdit 提交网格里正在编辑的单元格 → ApplyBarDetails 落盘当前悬浮条草稿
+// → 校验(按钮配置 / 导入的 XPath / 快捷键 / 锚定窗口条件)→ 逐字段写回 _settings → _store.Save。
+// 设置节拍(刷新间隔,毫秒;默认 300,范围 50–60000,见 AppSettings.DefaultRefreshIntervalMs):
+// · Ui.TreeRefreshIntervalMs —— 控件树 / 前台高亮重解析的刷新节奏。
+// · FloatingButton.RefreshIntervalMs —— 所有悬浮条跟随窗口 / 重算显示条件的刷新节奏。
+// ============================================================================
+using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
@@ -20,63 +44,120 @@ namespace pacs_win_uia.UI
///
public sealed class SettingsForm : Form
{
+ // 正在编辑的设置对象(草稿);保存成功后由 Result 交回调用方。
private readonly AppSettings _settings;
+ // 设置持久化(写盘;exe 目录不可写时用用户目录备份路径)。
private readonly AppSettingsStore _store;
+ // 命令执行器:命令页的「立即执行 / 启动定时 / 停止定时」用它。
private readonly CommandRunner _runner;
+ // 命令页「执行时机」列表草稿(保存时写回 _settings.Commands.Triggers)。
private readonly BindingList _triggers;
+ // 命令页左侧时机列表控件。
private ListBox _triggerList;
+ // 命令页右侧命令表格控件。
private DataGridView _commandGrid;
+ // 当前选中时机下的命令绑定列表(直接包住 trigger.Commands,改这里即改模型)。
private BindingList _currentCommands;
+ // 时机名称输入框。
private TextBox _triggerName;
+ // 时机种类下拉(启动/退出/定时/单次)。
private ComboBox _triggerKind;
+ // 时机间隔秒输入。
private NumericUpDown _triggerInterval;
+ // 时机启用勾选。
private CheckBox _triggerEnabled;
+ // 命令输出显示框(BuildCommandPage 末尾会重新指向页面底部的那个)。
private TextBox _outputBox;
+ // 命令页左右分隔条。
private SplitContainer _commandSplit;
+ // 悬浮按钮页左右分隔条。
private SplitContainer _barSplit;
+ // 界面页:选中窗口时是否自动读取控件树。
private CheckBox _autoReadTree;
+ // 界面页:是否用底色标出当前前台窗口。
private CheckBox _highlightForeground;
+ // 悬浮条草稿列表(保存时写回 _settings.FloatingButton.Bars)。
private readonly BindingList _bars;
+ // 悬浮按钮页左侧悬浮条列表控件。
private ListBox _barList;
+ // 悬浮按钮页按钮表格控件。
private DataGridView _buttonGrid;
+ // 当前悬浮条下的按钮绑定列表(包住 bar.Buttons)。
private BindingList _currentButtons;
+ // 悬浮条名称输入。
private TextBox _barName;
+ // 悬浮条启用勾选。
private CheckBox _barEnabled;
+ // 整体不透明度(20-100)。
private NumericUpDown _barOpacity;
+ // 背景透明度(0=沿用整体透明度)。
private NumericUpDown _barBackgroundOpacity;
+ // 按钮透明度(0=沿用整体透明度)。
private NumericUpDown _barControlOpacity;
+ // 相对锚定窗口 X 偏移。
private NumericUpDown _barOffsetX;
+ // 相对锚定窗口 Y 偏移。
private NumericUpDown _barOffsetY;
+ // 窗口条件三件套之一:进程名(可输入 + 下拉建议)。
private ComboBox _barProcess;
+ // 窗口条件三件套之二:窗口类名(可输入 + 下拉建议)。
private ComboBox _barClass;
+ // 窗口条件三件套之三:标题关键词(可输入 + 下拉建议)。
private ComboBox _barTitle;
+ // 「刷新窗口建议」按钮。
private Button _refreshWindowSuggestions;
+ // 「检测显示条件(只读)」按钮。
private Button _checkBarConditions;
+ // 窗口建议读取状态说明标签。
private Label _windowSuggestionStatus;
+ // 悬浮条显示条件检测结果文本框。
private TextBox _barCheckStatus;
+ // 后台枚举出的顶层窗口建议快照(供三个下拉填充)。
private IList _suggestedWindows = new List();
+ // 草稿版本号:每次修改条件或切换悬浮条自增;后台检测回来时用它丢弃过期结果。
private int _barEditVersion;
+ // 防止窗口建议刷新重入/并发。
private bool _refreshingSuggestions;
+ // 防止显示条件检测重入/并发。
private bool _checkingConditions;
+ // 「窗口可见且未被遮挡时才显示」勾选。
private CheckBox _barRequireVisible;
+ // 悬浮条条件/校验摘要标签(缺失条件、按钮配置错误等)。
private Label _barConditionLabel;
+ // 批量程序化赋值时的抑制开关:为 true 时各控件的 Changed 不回写草稿,避免
+ // 「载入数据→触发事件→互相覆盖/误标脏」的循环。
private bool _suppressBarEvents;
+ // 界面页:控件树最大深度。
private NumericUpDown _treeDepth;
+ // 界面页:控件树最大节点数。
private NumericUpDown _treeNodes;
+ // 界面页:控件树读取超时秒。
private NumericUpDown _treeTimeout;
+ // 界面页:控件树/高亮重解析刷新间隔(毫秒,默认300)。
private NumericUpDown _treeRefreshInterval;
+ // 悬浮按钮页:所有悬浮条跟随/显示条件刷新间隔(毫秒,默认300)。
private NumericUpDown _floatingRefreshInterval;
+ // 界面页:无界面读取默认等待超时秒。
private NumericUpDown _readTimeout;
+ // 界面页:无界面读取时跳过已停用的监控条目。
private CheckBox _skipDisabled;
+ // OCR 页:是否启用 OCR。
private CheckBox _ocrEnabled;
+ // OCR 页:服务地址(默认 http://127.0.0.1:8000)。
private TextBox _ocrBaseUrl;
+ // OCR 页:最小置信度(0-1)。
private NumericUpDown _ocrConfidence;
+ // OCR 页:单次识别总超时秒(含排队)。
private NumericUpDown _ocrTimeout;
+ // OCR 页:识别时是否保存截图。
private CheckBox _ocrSaveScreenshots;
+ // OCR 页:截图保存目录(留空 = exe 目录下 screenshots)。
private TextBox _ocrDirectory;
+ // 构造:参数兜底 + Normalize;把设置复制成草稿(_triggers/_bars),再搭出 5 个页面与
+ // 底部按钮栏。注意「保存」用 Click 事件,「取消」用 DialogResult.Cancel 直接关闭。
public SettingsForm(AppSettings settings, AppSettingsStore store, CommandRunner runner)
{
_settings = settings ?? AppSettings.CreateDefault();
@@ -95,6 +176,7 @@ namespace pacs_win_uia.UI
Size = new Size(1200, 900);
ShowInTaskbar = false;
+ // 5 个分页:关于 / 界面 / 悬浮按钮 / 命令 / OCR(顺序即显示顺序)。
var tabs = new TabControl { Dock = DockStyle.Fill };
tabs.TabPages.Add(BuildAboutPage());
tabs.TabPages.Add(BuildUiPage());
@@ -128,6 +210,7 @@ namespace pacs_win_uia.UI
Visible = false
};
+ // 排序即页面层级:tabs 填满中间,_outputBox 停靠底部(命令输出),buttons 在更底部。
Controls.Add(tabs);
Controls.Add(_outputBox);
Controls.Add(buttons);
@@ -140,6 +223,8 @@ namespace pacs_win_uia.UI
}
}
+ // 加载时:先定尺寸(恢复上次位置或按屏幕自适应),再设分隔条(其距离依赖真实宽度),
+ // 最后在后台拉取窗口建议。分隔条必须在有真实尺寸后再设,否则构造期设置会抛异常。
///
/// SplitterDistance is validated against the panel minimums on every assignment, so the
/// minimums are only tightened once the container has its real size. Setting them in the
@@ -156,6 +241,7 @@ namespace pacs_win_uia.UI
RefreshWindowSuggestionsAsync();
}
+ // 打开时若有记住的位置且仍落在某块屏幕上就恢复;否则(首次或显示器被拔掉)居中。
///
/// Opens where the operator left it. The first time (or when the remembered place is no longer
/// on any screen, e.g. a monitor was removed) the dialog is centred on the screen it belongs to.
@@ -186,6 +272,7 @@ namespace pacs_win_uia.UI
screen.Top + Math.Max(0, (screen.Height - Height) / 2));
}
+ // 判断给定矩形是否与任一屏幕的工作区相交(用于确认记住的位置仍可见)。
private static bool IntersectsAnyScreen(Rectangle bounds)
{
foreach (Screen screen in Screen.AllScreens)
@@ -199,6 +286,7 @@ namespace pacs_win_uia.UI
return false;
}
+ // 关闭时把窗口位置/尺寸记回 _settings.Ui(仅普通状态,最大化/最小化不记)。
/// Remembers the size and place so the next open lands where the operator put it.
private void RememberBounds()
{
@@ -213,6 +301,7 @@ namespace pacs_win_uia.UI
_settings.Ui.SettingsWindowHeight = Bounds.Height;
}
+ // 按屏幕工作区把窗口缩放到合适大小(约 72% 宽 / 84% 高,且不小于 MinimumSize)。
///
/// Fits the dialog to the screen. The old fixed 860x640 was smaller than the 命令 page needs:
/// a trigger's command list showed only its first line.
@@ -229,6 +318,7 @@ namespace pacs_win_uia.UI
+ workingArea.Width + "x" + workingArea.Height + ")");
}
+ // 按比例设置分隔条位置,并把两侧最小尺寸收敛到不违反布局的合法值(越界则记日志、忽略)。
private static void ApplySplitter(SplitContainer split, double ratio, int minimum1, int minimum2)
{
if (split == null)
@@ -253,12 +343,14 @@ namespace pacs_win_uia.UI
}
}
+ // 编辑后的设置对象;仅当对话框返回 OK 时才有意义(MainForm 据此应用新设置)。
/// The edited settings; only meaningful when the dialog returned OK.
public AppSettings Result
{
get { return _settings; }
}
+ // 深拷贝悬浮条列表做草稿:连其中的导入条件也走 CopyCondition 复制,避免改动污染原设置。
private static IList CopyBars(IList source)
{
var copy = new List();
@@ -312,6 +404,7 @@ namespace pacs_win_uia.UI
return copy;
}
+ // 深拷贝「执行时机」列表(含各自的命令)做草稿。
private static IList CopyTriggers(IList source)
{
var copy = new List();
@@ -358,6 +451,7 @@ namespace pacs_win_uia.UI
return copy;
}
+ // 深拷贝命令列表(供复制时机时使用)。
private static IList CopyCommands(IList source)
{
var copy = new List();
@@ -387,6 +481,7 @@ namespace pacs_win_uia.UI
// ------------------------------------------------------------------ pages
+ // 构建「关于」页:只读的版本/能力边界/配置路径/安全说明,无输入字段。
private TabPage BuildAboutPage()
{
var page = new TabPage("关于");
@@ -427,6 +522,8 @@ namespace pacs_win_uia.UI
return page;
}
+ // 构建「界面」页:控件树/高亮/读取相关的开关与数字输入(字段见顶部说明),
+ // 保存时写回 _settings.Ui.* 与 _settings.Read.*。
private TabPage BuildUiPage()
{
var page = new TabPage("界面");
@@ -471,6 +568,7 @@ namespace pacs_win_uia.UI
return page;
}
+ // 通用辅助:在 parent 里加一行「标签 + 数字输入」,并把值夹到 [minimum, maximum] 后返回输入框。
private NumericUpDown AddNumber(Control parent, string label, int value, int minimum, int maximum)
{
parent.Controls.Add(new Label { Text = label, AutoSize = true, Padding = new Padding(0, 8, 0, 0) });
@@ -485,6 +583,11 @@ namespace pacs_win_uia.UI
return box;
}
+ // 构建「悬浮按钮」页(本页最复杂):
+ // 左:悬浮条列表(_barList)+ 增删按钮;右:上半是详情表单(字段_条件_按钮/导入/检测),
+ // 下半是按钮网格(_buttonGrid)+ 增删按钮;页面底部还有「刷新间隔」输入。
+ // 详情表单里「窗口条件三件套」_barProcess/_barClass/_barTitle 是「可输入 + 下拉建议」组合框,
+ // 详见 AddBarSuggestionField。
private TabPage BuildFloatingPage()
{
var page = new TabPage("悬浮按钮");
@@ -534,6 +637,7 @@ namespace pacs_win_uia.UI
};
details.Controls.Add(conditionHint);
details.SetFlowBreak(conditionHint, true);
+ // 窗口条件三件套:field 0=进程名、1=窗口类、2=标题关键词(进程名选定会联动另两个建议)。
_barProcess = AddBarSuggestionField(details, "进程名", 180, 0);
_barClass = AddBarSuggestionField(details, "窗口类", 180, 1);
_barTitle = AddBarSuggestionField(details, "标题关键词", 220, 2);
@@ -576,6 +680,7 @@ namespace pacs_win_uia.UI
_barConditionLabel.MaximumSize = new Size(620, 0);
details.Controls.Add(_barConditionLabel);
details.SetFlowBreak(_barConditionLabel, true);
+ // 「检测显示条件(只读)」:只求值判断当前草稿能否显示,绝不执行按钮命令(见 CheckBarConditionsAsync)。
_checkBarConditions = new Button { Text = "检测显示条件(只读)", AutoSize = true };
_checkBarConditions.Click += delegate { CheckBarConditionsAsync(); };
details.Controls.Add(_checkBarConditions);
@@ -618,6 +723,8 @@ namespace pacs_win_uia.UI
};
_buttonGrid.Columns.Add(new DataGridViewCheckBoxColumn { HeaderText = "启用", DataPropertyName = "Enabled", FillWeight = 8 });
_buttonGrid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "按钮名称", DataPropertyName = "Label", FillWeight = 22 });
+ // 「点击执行操作」列:绑定 FloatingActionChoice 列表而不是枚举列表——这样单元格显示中文名,
+ // 但实际写回模型的仍是枚举值(直接绑枚举会在格子里显示 "PickControl")。
// Bound instead of a list of enum values: the cell must show the Chinese name of the action
// while still writing the enum into the model (a plain Items list would print "PickControl").
var actionColumn = new DataGridViewComboBoxColumn
@@ -635,6 +742,7 @@ namespace pacs_win_uia.UI
_buttonGrid.Columns.Add(actionColumn);
_buttonGrid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "快捷键", DataPropertyName = "Shortcut", FillWeight = 14 });
_buttonGrid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "点击执行命令", DataPropertyName = "CommandLine", FillWeight = 30 });
+ // 忽略网格绑定的数据错误(如单元格值无法转换),只标记已处理,避免弹框或中断编辑。
_buttonGrid.DataError += delegate(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
@@ -678,6 +786,7 @@ namespace pacs_win_uia.UI
WrapContents = false,
Padding = new Padding(6)
};
+ // 页面底部的刷新间隔(毫秒,默认 300,范围由 AppSettings 常量限定)。
_floatingRefreshInterval = AddNumber(refreshPanel,
"所有悬浮条跟随/显示条件刷新间隔(毫秒,默认300):",
_settings.FloatingButton.RefreshIntervalMs,
@@ -688,6 +797,7 @@ namespace pacs_win_uia.UI
return page;
}
+ // 建一个「不可换行」的子 FlowLayoutPanel 分组,保证标签和它的输入框始终在同一行。
///
/// One label + input pair. The pair is wrapped in its own flow panel so that a wrapping row
/// cannot leave the caption at the end of one line and its input at the start of the next.
@@ -706,6 +816,7 @@ namespace pacs_win_uia.UI
return group;
}
+ // 加一行普通文本框字段;每次输入都会通过 ApplyBarDetails 即时回写当前悬浮条草稿。
private TextBox AddBarField(Control parent, string label, int width)
{
FlowLayoutPanel group = AddBarGroup(parent);
@@ -716,10 +827,15 @@ namespace pacs_win_uia.UI
return box;
}
+ // 下拉建议项:Value 是要写进输入框的「实际值」,ToString() 是列表里显示的友好描述。
+ // 二者刻意分开:输入框只存真实条件值,列表则展示进程/类/标题等更多信息。
private sealed class WindowSuggestion
{
+ // 该建议对应的原始窗口信息(选定后用于联动填充其它条件)。
internal NativeWindowInfo Window;
+ // 实际条件值(进程名 / 类名 / 标题之一),即下拉的 DisplayMember/ValueMember。
public string Value { get; set; }
+ // 下拉列表里显示的友好描述(不是写入模型的值)。
public override string ToString()
{
return Value + " — " + (string.IsNullOrEmpty(Window.Title) ? "(无标题)" : Window.Title)
@@ -728,16 +844,22 @@ namespace pacs_win_uia.UI
}
}
+ // 建一个「窗口条件」输入框:既可直接键入,也可从下拉建议里选。
+ // 关键:DisplayMember/ValueMember 都设为 "Value",所以——无论是下拉选中还是手输——
+ // 写进编辑框和模型的都是「实际值」(进程名/类名/标题),而列表里通过 DrawItem 显示更丰富的描述。
+ // 参数 field:0=进程名、1=窗口类、2=标题关键词(决定用窗口的哪个字段做建议值)。
private ComboBox AddBarSuggestionField(Control parent, string label, int width, int field)
{
FlowLayoutPanel group = AddBarGroup(parent);
group.Controls.Add(new Label { Text = label, AutoSize = true, Padding = new Padding(6, 8, 0, 0) });
+ // DropDown(不是 DropDownList):允许手输任意值;OwnerDrawFixed 用于自定义列表绘制。
var box = new ComboBox
{
Width = width, DropDownStyle = ComboBoxStyle.DropDown,
DropDownWidth = 780, IntegralHeight = false, MaxDropDownItems = 14,
DisplayMember = "Value", ValueMember = "Value", DrawMode = DrawMode.OwnerDrawFixed
};
+ // 自绘列表:下拉列表里画 WindowSuggestion.ToString() 的友好描述;编辑框区域只画实际值。
// Native selection copies DisplayMember into the EDIT *after* SelectionChangeCommitted.
// Keep that text raw and draw the richer description only in the drop-down list. Clearing
// SelectedIndex during commit makes the native CBN_SELCHANGE overwrite the EDIT with "".
@@ -753,20 +875,27 @@ namespace pacs_win_uia.UI
}
e.DrawFocusRectangle();
};
+ // 手动键入时即时回写草稿;程序化赋值期间由 _suppressBarEvents 抑制,避免循环。
box.TextChanged += delegate
{
if (_suppressBarEvents) return;
ApplyBarDetails();
};
+ // 从下拉里「选定」一项时触发。特别重要:本处理里【绝不能】把 SelectedIndex 清成 -1,
+ // 因为 WinForms 原生的 CBN_SELCHANGE 会在提交完成后再把 DisplayMember 写回编辑框,
+ // 清空 SelectedIndex 会让编辑框被 "" 覆盖(这就是「选完就变空」的成因)。
box.SelectionChangeCommitted += delegate
{
if (_suppressBarEvents) return;
var suggestion = box.SelectedItem as WindowSuggestion;
if (suggestion == null) return;
+ // 保留原生选中项直到 WinForms 处理完 CBN_SELCHANGE/CLOSEUP;
+ // DisplayMember 已保证编辑框拿到的是实际值,这里再显式写一次同样的值。
// Preserve the native selection until WinForms finishes CBN_SELCHANGE/CLOSEUP.
// DisplayMember already ensures the editor receives the actual value.
box.Text = suggestion.Value;
+ // 选定建议只为「空白字段」补默认值:用户手输过的条件优先,不被覆盖。
// A choice supplies useful defaults only for blank fields. Typed conditions win.
if (field == 0)
{
@@ -783,6 +912,7 @@ namespace pacs_win_uia.UI
return box;
}
+ // 程序化设置建议框的值:暂时抑制事件,并把光标移到末尾;供载入/联动填充使用,不触发回写。
private void SetSuggestionValue(ComboBox box, string raw)
{
if (box == null) return;
@@ -801,13 +931,16 @@ namespace pacs_win_uia.UI
}
}
+ // 取建议框里要持久化的实际值:始终用编辑框文本(去掉首尾空白)。
private static string SuggestionValue(ComboBox box)
{
+ // 绝不能用 SelectedItem.ToString() 来取值——那是在列表里展示的友好描述,不是实际条件值。
// Never derive a persisted value from SelectedItem.ToString(): it is intentionally a
// friendly description of a window, not the process/class/title condition itself.
return box == null ? string.Empty : (box.Text ?? string.Empty).Trim();
}
+ // 后台枚举顶层窗口作为下拉建议(不阻塞 UI、不改动已填条件);完成后刷新三个建议框。
private async void RefreshWindowSuggestionsAsync()
{
if (_refreshingSuggestions || IsDisposed) return;
@@ -836,6 +969,8 @@ namespace pacs_win_uia.UI
}
}
+ // 重建三个建议框的候选项:includeProcess 为 true 时也重填「进程名」框,
+ // 否则只按当前进程名联动刷新「窗口类」「标题关键词」。全程抑制事件,避免误回写。
private void RebuildWindowSuggestions(bool includeProcess)
{
if (_barProcess == null || _barClass == null || _barTitle == null) return;
@@ -851,8 +986,12 @@ namespace pacs_win_uia.UI
finally { _suppressBarEvents = previous; }
}
+ // 用 _suggestedWindows 重填某个建议框(可按 process 过滤),并尽量保留用户当前输入的
+ // 文本与光标/选区——即「新到的建议绝不覆盖正在输入的内容」。
private void FillWindowSuggestions(ComboBox box, int field, string process)
{
+ // 在刷新「完成时」才快照当前文本,而不是异步枚举开始前:这样期间的手输(含光标位置)
+ // 始终优先于刚到的建议内容。
// Snapshot at refresh completion, not before the asynchronous enumeration: current
// edits (including whitespace/caret) always win over the newly arrived suggestions.
string text = box.Text;
@@ -877,6 +1016,8 @@ namespace pacs_win_uia.UI
finally { box.EndUpdate(); }
}
+ // 草稿被修改(或切换了悬浮条)时调用:自增 _barEditVersion 使仍在后台跑的检测结果作废,
+ // 并提示「配置已修改,请重新检测」。名称只用于显示,不是按钮或定位条件。
private void InvalidateBarCheck()
{
_barEditVersion++;
@@ -884,6 +1025,9 @@ namespace pacs_win_uia.UI
_barCheckStatus.Text = "配置已修改或已切换悬浮条,请重新检测。名称仅用于显示,不是按钮或定位条件。";
}
+ // 「检测显示条件(只读)」入口:先把正在编辑的单元格提交、把草稿落盘,再复制一份快照在后台
+ // 调用 FloatingBarManager.CheckDisplayConditions —— 只判断当前能否显示,绝不执行按钮命令。
+ // 带回发起时的版本号,若期间草稿又变了则丢弃这次结果(避免显示过期判定)。超过 10 秒给出提示。
private async void CheckBarConditionsAsync()
{
if (_checkingConditions) return;
@@ -891,7 +1035,9 @@ namespace pacs_win_uia.UI
ApplyBarDetails();
FloatingBarDefinition bar = SelectedBar();
if (bar == null) return;
+ // 用副本检测:后台线程不直接读正在被 UI 编辑的对象。
FloatingBarDefinition snapshot = CopyBars(new[] { bar })[0];
+ // 记下发起时版本;回来时若 _barEditVersion 已变,说明草稿改了,作废。
int version = _barEditVersion;
_checkingConditions = true;
_checkBarConditions.Enabled = false;
@@ -922,6 +1068,8 @@ namespace pacs_win_uia.UI
}
}
+ // 通过一次 JSON 序列化/反序列化做「深拷贝」:导入监控项 path 时得到的是独立副本,
+ // 之后原监控项被修改或停用都不会影响已经导入的悬浮条条件。
private static ControlMonitorDefinition CopyCondition(ControlMonitorDefinition source)
{
if (source == null) return null;
@@ -934,6 +1082,7 @@ namespace pacs_win_uia.UI
}
}
+ // 加一行数字字段(透明度/偏移用);值变化即回写草稿。
private NumericUpDown AddBarNumber(Control parent, string label, int minimum, int maximum)
{
FlowLayoutPanel group = AddBarGroup(parent);
@@ -944,6 +1093,7 @@ namespace pacs_win_uia.UI
return box;
}
+ // 重建左侧悬浮条列表(尽量保留原选中项;列表空时清空详情)。
private void RefreshBarList()
{
int previous = _barList.SelectedIndex;
@@ -963,11 +1113,13 @@ namespace pacs_win_uia.UI
}
}
+ // 取当前选中的悬浮条草稿(可能为 null)。
private FloatingBarDefinition SelectedBar()
{
return _barList.SelectedItem as FloatingBarDefinition;
}
+ // 新增一条悬浮条(带一个默认「定位控件」按钮)并选中它。
private void AddBar()
{
var bar = new FloatingBarDefinition { Name = "悬浮条" + (_bars.Count + 1) };
@@ -981,6 +1133,7 @@ namespace pacs_win_uia.UI
_barList.SelectedIndex = _barList.Items.Count - 1;
}
+ // 删除当前悬浮条(先弹确认框)。
private void RemoveBar()
{
FloatingBarDefinition bar = SelectedBar();
@@ -999,6 +1152,8 @@ namespace pacs_win_uia.UI
RefreshBarList();
}
+ // 选中悬浮条后:把它的字段载入右侧表单、把按钮绑到网格;其间 _suppressBarEvents=true
+ // 抑制这些控件因载入而触发的回写(否则会把「载入」误当成「用户修改」)。
private void LoadSelectedBar()
{
if (_suppressBarEvents) return;
@@ -1041,6 +1196,8 @@ namespace pacs_win_uia.UI
RefreshBarConditionLabel();
}
+ // 把右侧表单里的字段回写到「当前悬浮条草稿」。详情控件的 Changed 事件都连到这里;
+ // _suppressBarEvents 为真(载入/批量赋值中)时直接跳过,避免误回写。
private void ApplyBarDetails()
{
if (_suppressBarEvents)
@@ -1066,6 +1223,8 @@ namespace pacs_win_uia.UI
bar.WindowTitleKeyword = SuggestionValue(_barTitle);
bar.RequireWindowVisible = _barRequireVisible.Checked;
+ // 替换被选中的列表项会触发 WinForms 的 SelectedIndexChanged;刷新列表行文字时
+ // 用 _suppressBarEvents 抑制它,避免重新绑定网格/重置编辑器而丢掉正在进行的编辑。
// Replacing the selected list item raises SelectedIndexChanged on WinForms. Do not
// rebind the grid/reset editors (and lose an in-progress edit) while refreshing its label.
_suppressBarEvents = true;
@@ -1080,6 +1239,7 @@ namespace pacs_win_uia.UI
RefreshBarConditionLabel();
}
+ // 给当前悬浮条新增一个按钮(默认「定位控件」),刷新网格后回写草稿。
private void AddFloatingButton()
{
FloatingBarDefinition bar = SelectedBar();
@@ -1097,6 +1257,7 @@ namespace pacs_win_uia.UI
ApplyBarDetails();
}
+ // 删除按钮网格中当前行的按钮。
private void RemoveFloatingButton()
{
if (_currentButtons == null || _buttonGrid.CurrentRow == null)
@@ -1112,6 +1273,8 @@ namespace pacs_win_uia.UI
}
}
+ // 「导入监控项 path」:弹窗从已保存的监控项里挑一个,把它的定位条件导入当前悬浮条。
+ // 导入的是【副本】(CopyCondition 深拷贝),原监控项后续改动/停用都不影响这里。
/// Copies a saved monitor entry's locator into the bar's condition ("导入 path").
private void ImportCondition()
{
@@ -1178,7 +1341,10 @@ namespace pacs_win_uia.UI
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
+ // 存入的是拷贝出来的副本,不是对监控项对象的引用。
bar.ImportedCondition = CopyCondition(selected);
+ // 只有在悬浮条本来没有任何窗口条件时,才用被导入监控项的窗口信息补齐锚定条件;
+ // 否则「手输的进程名 + 别的监控项的类/标题」会拼出永远匹配不上的组合。
// Derive a complete anchor only when none was supplied. Mixing a hand-entered
// process with another monitor's class/title silently creates impossible conditions.
if (!FloatingBarManager.HasWindowConditions(bar.ProcessName, bar.WindowClass, bar.WindowTitleKeyword))
@@ -1211,6 +1377,7 @@ namespace pacs_win_uia.UI
}
}
+ // 刷新条件摘要标签:启停状态、启用按钮数、按钮配置错误、导入的 XPath 及窗口条件是否缺失。
private void RefreshBarConditionLabel()
{
if (_barConditionLabel == null) return;
@@ -1240,6 +1407,8 @@ namespace pacs_win_uia.UI
_barConditionLabel.Text = status;
}
+ // 构建「命令」页:左侧执行时机列表(_triggerList),右侧该时机的命令网格(_commandGrid),
+ // 中间是「立即执行 / 启动定时 / 停止定时」操作行与安全提示,底部是命令输出框。
private TabPage BuildCommandPage()
{
var page = new TabPage("命令");
@@ -1273,6 +1442,8 @@ namespace pacs_win_uia.UI
_triggerName.TextChanged += delegate { ApplyTriggerDetails(); };
detailLayout.Controls.Add(_triggerName);
detailLayout.Controls.Add(new Label { Text = "时机", AutoSize = true, Padding = new Padding(8, 8, 0, 0) });
+ // 时机种类:下拉项的【顺序必须与 CommandTriggerKind 枚举整数值一致】
+ // (载入时用 SelectedIndex=(int)trigger.Kind,保存时再 (CommandTriggerKind)SelectedIndex)。
_triggerKind = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = 120 };
_triggerKind.Items.AddRange(new object[]
{
@@ -1310,6 +1481,7 @@ namespace pacs_win_uia.UI
split.Panel2.Controls.Add(right);
layout.Controls.Add(split);
+ // 操作行:立即执行当前时机的命令 / 按当前配置启动定时命令 / 停止定时命令。
var actions = new FlowLayoutPanel { Dock = DockStyle.Fill, WrapContents = false };
var runNow = new Button { Text = "立即执行当前时机的命令", AutoSize = true };
runNow.Click += delegate { RunSelectedTrigger(); };
@@ -1363,6 +1535,7 @@ namespace pacs_win_uia.UI
return page;
}
+ // 重建执行时机列表(尽量保留原选中项;列表空时清空右侧)。
/// Rebuilds the moment list and selects the first entry.
private void RefreshTriggerList()
{
@@ -1383,6 +1556,7 @@ namespace pacs_win_uia.UI
}
}
+ // 新增一个执行时机(默认单次)并选中它。
private void AddTrigger()
{
var trigger = new CommandTrigger
@@ -1395,6 +1569,7 @@ namespace pacs_win_uia.UI
_triggerList.SelectedIndex = _triggerList.Items.Count - 1;
}
+ // 删除当前执行时机及其下所有命令(先弹确认框)。
private void RemoveTrigger()
{
CommandTrigger trigger = _triggerList.SelectedItem as CommandTrigger;
@@ -1417,6 +1592,8 @@ namespace pacs_win_uia.UI
RefreshTriggerList();
}
+ // 选中时机后:把它的字段载入上方编辑器(期间 _suppressTriggerDetailEvents 抑制回写),
+ // 并把它的命令列表绑到右侧网格。
/// Shows the selected moment's commands and copies its fields into the editors.
private void LoadSelectedTrigger()
{
@@ -1441,13 +1618,16 @@ namespace pacs_win_uia.UI
_suppressTriggerDetailEvents = false;
}
+ // BindingList 直接包住 trigger 自己的命令列表,所以网格里的编辑就是改模型本身。
// BindingList wraps the trigger's own list, so edits land in the model directly.
_currentCommands = new BindingList(trigger.Commands);
_commandGrid.DataSource = _currentCommands;
}
+ // 载入时机字段时抑制编辑器的 Changed 回写(与 _suppressBarEvents 同理,只是针对命令页)。
private bool _suppressTriggerDetailEvents;
+ // 把时机编辑器里的字段回写到当前时机;末尾替换列表项以刷新行文字但保留选中。
private void ApplyTriggerDetails()
{
if (_suppressTriggerDetailEvents)
@@ -1466,12 +1646,14 @@ namespace pacs_win_uia.UI
trigger.IntervalSeconds = (int)_triggerInterval.Value;
trigger.Enabled = _triggerEnabled.Checked;
+ // 列表行显示的是 ToString(),所以要刷新行文字,同时保留选中项不丢。
// The list shows ToString(), so refresh the row text without losing the selection.
int index = _triggerList.SelectedIndex;
_triggerList.Items[index] = trigger;
_triggerList.SelectedIndex = index;
}
+ // 给当前时机新增一条命令(默认 echo hello,间隔沿用时机间隔)。
private void AddCommand()
{
var trigger = _triggerList.SelectedItem as CommandTrigger;
@@ -1490,6 +1672,7 @@ namespace pacs_win_uia.UI
_currentCommands.ResetBindings();
}
+ // 删除命令网格中当前行的命令。
private void RemoveCommand()
{
if (_currentCommands == null || _commandGrid.CurrentRow == null)
@@ -1504,6 +1687,7 @@ namespace pacs_win_uia.UI
}
}
+ // 「立即执行当前时机的命令」:逐条同步执行并显示结果(超时/失败/退出码)。
private void RunSelectedTrigger()
{
var trigger = _triggerList.SelectedItem as CommandTrigger;
@@ -1535,6 +1719,7 @@ namespace pacs_win_uia.UI
}
}
+ // 辅助:在 TableLayoutPanel 里加一行「左标签 + 右文本框」,返回其中文本框。
private TextBox AddCommandLine(TableLayoutPanel layout, string label, string value)
{
var panel = new Panel { Dock = DockStyle.Fill };
@@ -1546,6 +1731,7 @@ namespace pacs_win_uia.UI
return (TextBox)panel.Controls[0];
}
+ // 构建命令网格的列(启用/名称/命令行/工作目录/间隔秒/超时秒),绑定到命令列表。
private DataGridView BuildCommandGrid()
{
var grid = new DataGridView
@@ -1565,6 +1751,7 @@ namespace pacs_win_uia.UI
return grid;
}
+ // 构建「OCR」页:启用开关、服务地址、最小置信度、超时、截图开关与目录(字段见顶部说明)。
private TabPage BuildOcrPage()
{
var page = new TabPage("OCR");
@@ -1648,8 +1835,12 @@ namespace pacs_win_uia.UI
// ------------------------------------------------------------------ actions
+ // 「保存」主流程:提交正在编辑的单元格 → 落盘当前悬浮条草稿 → 校验(悬浮条按钮配置、
+ // 导入的 XPath、快捷键、锚定窗口条件)→ 逐字段写回 _settings → _store.Save 写盘。
+ // 任一步校验不过都会弹提示并中止(不写盘),对话框保持打开便于修正。
private void Save()
{
+ // 先提交网格中正在编辑的单元格,再取设置快照/校验,避免拿到半截编辑值。
// Commit the current cell before taking the settings snapshot or validating it.
if (!_buttonGrid.EndEdit() || !_commandGrid.EndEdit()) return;
ApplyBarDetails();
@@ -1671,6 +1862,7 @@ namespace pacs_win_uia.UI
return;
}
}
+ // ---- 界面页字段写回 _settings.Ui / _settings.Read
_settings.Ui.AutoReadTreeOnSelect = _autoReadTree.Checked;
_settings.Ui.HighlightForegroundWindow = _highlightForeground.Checked;
_settings.Ui.TreeMaxDepth = (int)_treeDepth.Value;
@@ -1681,7 +1873,9 @@ namespace pacs_win_uia.UI
_settings.Read.DefaultTimeoutSeconds = (int)_readTimeout.Value;
_settings.Read.SkipDisabled = _skipDisabled.Checked;
+ // ---- 悬浮条草稿写回
_settings.FloatingButton.Bars = new List(_bars);
+ // 现在就暴露坏掉的快捷键,而不是等到运行期静默注册不上。
// Surface broken shortcuts now instead of silently never registering them.
foreach (FloatingBarDefinition bar in _settings.FloatingButton.Bars)
{
@@ -1708,9 +1902,11 @@ namespace pacs_win_uia.UI
}
}
+ // ---- 命令页写回:网格直接包住各时机的列表,所以编辑早已落在 _triggers 上,这里只做整体替换。
// The grid wraps each trigger's own list, so the edits are already in _triggers.
_settings.Commands.Triggers = new List(_triggers);
+ // ---- OCR 页字段写回
_settings.Ocr.Enabled = _ocrEnabled.Checked;
_settings.Ocr.BaseUrl = _ocrBaseUrl.Text;
_settings.Ocr.MinConfidence = (double)_ocrConfidence.Value;
@@ -1718,6 +1914,7 @@ namespace pacs_win_uia.UI
_settings.Ocr.SaveScreenshots = _ocrSaveScreenshots.Checked;
_settings.Ocr.ScreenshotDirectory = _ocrDirectory.Text;
+ // ---- 写盘:失败(exe 目录与用户目录都不可写)则提示并中止。
if (!_store.Save(_settings))
{
MessageBox.Show(
@@ -1734,6 +1931,7 @@ namespace pacs_win_uia.UI
Close();
}
+ // 命令输出回调:若在非 UI 线程则切回 UI 线程,再追加到输出框(对话框关闭时静默忽略)。
private void AppendOutput(CommandOutputEventArgs e)
{
if (IsDisposed)
@@ -1758,6 +1956,7 @@ namespace pacs_win_uia.UI
ShowOutput((e.IsError ? "[stderr] " : "[out] ") + e.Text);
}
+ // 在输出框顶部插入一行带时间戳的文本(最新在上),并截断到 2 万字防止无限增长。
private void ShowOutput(string line)
{
_outputBox.Visible = true;
@@ -1768,6 +1967,7 @@ namespace pacs_win_uia.UI
}
}
+ // 用资源管理器打开给定文件所在目录(目录不存在或失败时弹提示)。
private static void OpenFolder(string filePath)
{
try
diff --git a/src/pacs_win_uia/UI/ShiftWheelScroll.cs b/src/pacs_win_uia/UI/ShiftWheelScroll.cs
index d777bfa..15fa202 100644
--- a/src/pacs_win_uia/UI/ShiftWheelScroll.cs
+++ b/src/pacs_win_uia/UI/ShiftWheelScroll.cs
@@ -4,6 +4,18 @@ using System.Runtime.InteropServices;
using System.Windows.Forms;
using pacs_win_uia.Interop;
+/*
+ * ShiftWheelScroll —— 全局“Shift+滚轮横向滚动”。
+ * 职责:作为 IMessageFilter 拦截 WM_MOUSEWHEEL;按住 Shift 时,按鼠标下方的窗口找到可横向
+ * 滚动的控件并把它横向滚动。这样窗口列表、控件树、属性区、各种列表都不用各自实现。
+ * 被谁调用:MainForm 构造函数中 Application.AddMessageFilter(_shiftWheel) 注册为全局过滤器。
+ * 交互清单:光标悬停在窗口列表 / 控件树 / 属性区 / 列表上,Shift+滚轮 → 内容左右滚动。
+ * DataGridView 自身已支持该行为,故被显式跳过。
+ * 要改什么就改哪里:
+ * - 滚动速度:LinesPerNotch(每格滚轮滚动的行数)。
+ * - 判定哪些控件算“可横向滚动”:FindScrollable。
+ */
+
namespace pacs_win_uia.UI
{
///
@@ -14,13 +26,19 @@ namespace pacs_win_uia.UI
///
public sealed class ShiftWheelScroll : IMessageFilter
{
+ // Windows 消息:鼠标滚轮。
private const int WM_MOUSEWHEEL = 0x020A;
+ // Windows 消息:横向滚动条命令。
private const int WM_HSCROLL = 0x0114;
+ // 横向滚动条命令:向左滚一行。
private const int SB_LINELEFT = 0;
+ // 横向滚动条命令:向右滚一行。
private const int SB_LINERIGHT = 1;
+ // 滚轮每一格(120 delta)对应的横向滚动行数。
private const int LinesPerNotch = 3;
+ // 消息过滤器入口:只处理 Shift+滚轮的 WM_MOUSEWHEEL;命中可横向滚动控件时吞掉消息并返回 true。
public bool PreFilterMessage(ref Message message)
{
if (message.Msg != WM_MOUSEWHEEL)
@@ -93,6 +111,8 @@ namespace pacs_win_uia.UI
/// Walks up from the control under the cursor to one that can scroll sideways. Controls with a
/// native scrollbar need WM_HSCROLL; a scrollable panel uses its scroll properties.
///
+ // 从光标下的控件向上回溯,找到能横向滚动的祖先:原生滚动条控件用 WM_HSCROLL,AutoScroll 面板用滚动属性;
+ // 遇到 DataGridView 直接返回 null(它自己处理 Shift+滚轮)。
private static Control FindScrollable(Control control, out bool native)
{
native = false;
diff --git a/tests/README.md b/tests/README.md
index 6ba25fb..5e9d6a2 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -1,5 +1,32 @@
# tests —— 可运行的测试夹具
+## 这些测试怎么跑、失败怎么办
+
+本目录有两块东西,目的不同:
+
+1. `uia-fixture/` —— 一个**独立进程**的真实 WinForms 窗口(`UiaFixture.exe`),用来让工具
+ 跨进程做 UIA 读取/拾取/定位的人工验证。UIA 在**同一进程内**自读自身控件树会崩溃,所以必须
+ 跨进程。构建并启动:`tests\run-fixture.cmd`(默认 Debug,可传 `Release`)。
+2. `regression/RegressionTests.csproj` —— 自动化回归测试(net48 控制台程序),在纯内存快照或
+ 本进程自建控件上跑断言,覆盖 XPath 定位、持久化/迁移、控件树增量刷新、悬浮条显示条件等。
+ 它**不**用 UIA 读自身控件树(会崩溃)。
+
+跑回归测试(不要在本目录直接 `dotnet build`,`src` 的 `bin\Debug` 可能被正在运行的工具进程锁定):
+
+```bat
+:: 用隔离的 OutputPath 构建,随后直接运行生成的 exe
+dotnet msbuild tests\regression\RegressionTests.csproj -t:Build -p:Configuration=Debug ^
+ -p:OutputPath=%TEMP%\pacs-regression\ -v:minimal
+%TEMP%\pacs-regression\RegressionTests.exe
+```
+
+- **退出码**:`0` = 全部用例通过;`1` = 存在失败(便于脚本/CI 判断)。
+- **失败怎么办**:在输出里找 `FAIL <用例名>`,其下会打印异常的 message(含 expected/actual)。
+ 按用例名到 `regression/*Tests.cs` 的 `Register(...)` 里定位对应方法。下拉/刷新类用例可设
+ 环境变量 `PACS_REGRESSION_SCREENSHOTS=<目录>`,失败或关键步骤会自动把窗体截图写入该目录以便比对。
+- **部分跳过是正常的**:个别断言依赖桌面上是否存在其他进程的窗口(如遮挡诊断的外部窗口用例),
+ 缺失时会打印 `(... skipped)` 并跳过,不算失败。
+
真实 PACS/OCS 客户端要么不暴露 UIA(CEF 套壳),要么树太大没法人工核对。
这里放一个**普通 WinForms 窗口**,控件类型、名称、层级都是已知的,用来验证本工具的读取链路。
diff --git a/tests/regression/FloatingConditionsTests.cs b/tests/regression/FloatingConditionsTests.cs
index f186cae..95c06ec 100644
--- a/tests/regression/FloatingConditionsTests.cs
+++ b/tests/regression/FloatingConditionsTests.cs
@@ -1,3 +1,15 @@
+// =====================================================================================
+// FloatingConditionsTests —— 悬浮条「检测显示条件」的窗口匹配与配置校验回归。
+//
+// 覆盖范围:FloatingBarManager.FindConditionWindow(进程/类名/标题线索必须全部满足且
+// 命中唯一窗口,进程名大小写/“.exe”后缀归一化)与 CheckDisplayConditions
+// (禁用、无按钮、无锚点、旧格式导入路径等不显示原因必须给出可读诊断)。
+//
+// 为什么这样测:窗口列表是手工构造的 NativeWindowInfo 纯数据快照,不枚举真实窗口、
+// 不做 UIA 调用,因此结果稳定可重复。
+//
+// 新增用例:加到 Register(...) 列表并实现 private static void 方法,断言走 Check.*。
+// =====================================================================================
using System;
using System.Collections.Generic;
using pacs_win_uia.Models;
@@ -9,7 +21,9 @@ namespace PacsWinUia.RegressionTests
{
public static void Register(IList> tests)
{
+ // 防:窗口线索被放宽成 OR / 命中歧义时武断取第一个 / 空线索也能匹配。
tests.Add(new KeyValuePair("Floating conditions require all supplied clues and unique window", WindowConditions));
+ // 防:禁用/空/无锚点等配置错误直接静默不显示,而不给出可读原因。
tests.Add(new KeyValuePair("Floating display explains missing configuration before provider calls", InvalidConfiguration));
}
diff --git a/tests/regression/PathTests.cs b/tests/regression/PathTests.cs
index bc97b45..42c2813 100644
--- a/tests/regression/PathTests.cs
+++ b/tests/regression/PathTests.cs
@@ -1,3 +1,16 @@
+// =====================================================================================
+// PathTests —— XPath 定位的解析 / 生成 / 转义 / 歧义 / 拒绝 回归。
+//
+// 覆盖范围:ControlPath 的 Select / SelectUnique / Build / PreparePaths / Quote /
+// ValidateSyntax,以及 ControlLocatorBuilder 与 ControlLocatorService.ResolveFromTree
+// 的端到端行为。
+//
+// 为什么这样测:全部跑在纯内存 ControlTreeNode 快照(TreeFixture)上,
+// 不触碰真实 UIA / HWND / provider——UIA 自读本进程会崩溃,这里根本不需要它。
+//
+// 新增用例:在 Register(...) 的列表里加一行「用例名 → 委托」,再在本类实现一个
+// private static void 方法;断言统一用 Check.Matches / Rejected / Equal / Same。
+// =====================================================================================
using System;
using System.Collections.Generic;
using pacs_win_uia.Models;
@@ -9,16 +22,27 @@ namespace PacsWinUia.RegressionTests
{
public static void Register(IList> tests)
{
+ // 防:XPath 属性 / contains / 轴 / 位置谓词解析回归。
tests.Add(new KeyValuePair("XPath attributes, contains, axes and positional predicates", XPathQueries));
+ // 防:重复 AutomationId 与结构序号导致路径不唯一、roundtrip 丢节点。
tests.Add(new KeyValuePair("All nodes roundtrip with duplicate IDs and structural indices", AllNodesRoundtrip));
+ // 防:祖先 Name 变化后生成路径失效(生成路径不得依赖可变的 Name)。
tests.Add(new KeyValuePair("Generated paths survive names changing on every ancestor", ChangingNames));
+ // 防:ClassName 兜底与「稳定祖先锚定」能力丢失。
tests.Add(new KeyValuePair("Class-qualified paths and stable ancestor anchors", ClassAndAnchor));
+ // 防:含单双引号 / 斜杠 / 中文的名称转义错误。
tests.Add(new KeyValuePair("XPath quoting for both quotes, slash and Chinese", Escaping));
+ // 防:旧显示格式 / 结构化旧路径被当作 XPath 执行。
tests.Add(new KeyValuePair("Old display and structured paths are not executed", RejectLegacy));
+ // 防:非法 / 标量 / 属性型 XPath 被静默接受。
tests.Add(new KeyValuePair("Invalid, scalar and attribute XPath rejected", RejectedPaths));
+ // 防:歧义路径被武断解析成第一个节点。
tests.Add(new KeyValuePair("Ambiguity never resolves to an arbitrary first node", AmbiguousPaths));
+ // 防:陈旧的 RuntimeId / locator 提示反过来覆盖当前 XPath。
tests.Add(new KeyValuePair("Changed XPath is authoritative over stale locator hints", AuthoritativeXPath));
+ // 防:根节点、外部节点、不完整快照等边界处理回归。
tests.Add(new KeyValuePair("Root, outsider and incomplete snapshot handling", RootAndIncomplete));
+ // 防:XPath 解析丢失 MSAA / Win32 载荷或来源标记。
tests.Add(new KeyValuePair("XPath resolution preserves MSAA and Win32 payloads", OtherSources));
}
diff --git a/tests/regression/PersistenceTests.cs b/tests/regression/PersistenceTests.cs
index af87a06..ee410dc 100644
--- a/tests/regression/PersistenceTests.cs
+++ b/tests/regression/PersistenceTests.cs
@@ -1,3 +1,15 @@
+// =====================================================================================
+// PersistenceTests —— 监控条目与设置的持久化 / 迁移 / 缺省值 回归。
+//
+// 覆盖范围:ControlMonitorStore 的 Save/Load(XPath 不落盘动态字段、拒绝旧格式写入)、
+// AppSettingsStore 的 Load/Save(旧 UiaPath 读取、缺失区段与刷新间隔缺省值、
+// 悬浮条 Enabled/RequireWindowVisible 的“缺省启用 vs 显式停用”区分)。
+//
+// 为什么这样测:全部在临时目录里读写 JSON 文件、用内存对象断言,不涉及 UIA / GUI;
+// 每个用例用 TemporaryDirectory 隔离,绝不读写真实用户配置。
+//
+// 新增用例:加到 Register(...) 列表并实现 private static void 方法,断言走 Check.*。
+// =====================================================================================
using System;
using System.Collections.Generic;
using System.IO;
@@ -11,9 +23,13 @@ namespace PacsWinUia.RegressionTests
{
public static void Register(IList> tests)
{
+ // 防:RuntimeId/Value 等动态字段被写进 JSON、Obsolete 标志残留、Disabled 未落盘。
tests.Add(new KeyValuePair("Store saves XPath without dynamic UIA fields and copies flags", StoreXPath));
+ // 防:旧 UiaPath 定义被读入后又被静默改写/覆盖旧文件,或修正后不持久化。
tests.Add(new KeyValuePair("Store reads legacy UiaPath definitions", StoreLegacy));
+ // 防:设置缺省刷新间隔不再是 300ms,或缺失的区段未被补全。
tests.Add(new KeyValuePair("Settings missing refresh interval defaults to 300", SettingsDefault));
+ // 防:悬浮条缺省启用被误判为显式停用(或反之)。
tests.Add(new KeyValuePair("Floating JSON missing defaults differs from explicit disabled", FloatingDefaults));
}
diff --git a/tests/regression/Program.cs b/tests/regression/Program.cs
index 3a44078..45e3ff0 100644
--- a/tests/regression/Program.cs
+++ b/tests/regression/Program.cs
@@ -1,3 +1,28 @@
+// =====================================================================================
+// pacs_win_uia 回归测试工程(net48 控制台程序,AssemblyName = RegressionTests)。
+//
+// 覆盖范围:
+// - XPath 定位的解析 / 生成 / 转义 / 歧义与拒绝 ................ PathTests
+// - 监控条目与设置的持久化、旧格式迁移、缺省值 ................ PersistenceTests
+// - 控件树增量刷新时的节点身份保持 ............................ TreeRefreshTests
+// - 悬浮条显示条件的窗口匹配与配置校验 ........................ FloatingConditionsTests
+// - 悬浮条进程/类名/标题下拉的原生鼠标与键盘选择 .............. SettingsComboBoxTests
+// - 遮挡诊断里“本工具自身窗口不算遮挡” ........................ WindowVisibilityTests
+//
+// 为什么这样测(重要):
+// 用例都在**纯内存快照**(ControlTreeNode)或本进程自建的 WinForms 控件上运行,
+// 绝不调用 UIA 去读本进程自己的控件树——UIA 自读会导致进程崩溃(见 MEMORY:
+// in-process UIA self-reads segfault)。凡是必须走真实 UIA 的场景,请改用
+// tests/uia-fixture 的独立进程做跨进程验证,不要在这里自读。
+//
+// 新增用例加在哪里:
+// 按主题加到对应 *Tests.cs 的 Register(...) 列表里,并在该文件里实现一个
+// private static void 方法;断言统一走 Check.*,不要自己 throw 或手写 Console 判断。
+//
+// Register 模式怎么用:
+// 每个测试类提供 static Register(IList>),
+// 把「用例名 → 委托」成对登记;Main 依次调用它们收集全部用例,再逐个执行并统计。
+// =====================================================================================
using System;
using System.Collections.Generic;
using System.IO;
@@ -9,11 +34,18 @@ namespace PacsWinUia.RegressionTests
{
internal static class Program
{
+ // 运行方式:不要在本目录直接 dotnet build(src 的 bin\Debug 可能被正在运行的工具进程锁定)。
+ // 用一个隔离的 OutputPath 构建,再直接运行生成的 exe:
+ // dotnet msbuild tests\regression\RegressionTests.csproj -t:Build -p:Configuration=Debug
+ // -p:OutputPath=<隔离目录>\ -v:minimal
+ // <隔离目录>\RegressionTests.exe
+ // 退出码:0 = 全部用例通过;1 = 有任一用例失败(见 Main 末尾的 return)。
[STAThread]
private static int Main()
{
Console.OutputEncoding = new UTF8Encoding(false);
var tests = new List>();
+ // 各测试类把自己的用例登记进同一张表(顺序即执行顺序,彼此独立无共享状态)。
PathTests.Register(tests);
PersistenceTests.Register(tests);
TreeRefreshTests.Register(tests);
@@ -21,6 +53,7 @@ namespace PacsWinUia.RegressionTests
SettingsComboBoxTests.Register(tests);
WindowVisibilityTests.Register(tests);
int passed = 0;
+ // 逐个执行登记的用例:通过则 PASS 并累加,抛异常则 FAIL 并打印完整异常。
foreach (var test in tests)
{
try
@@ -36,28 +69,35 @@ namespace PacsWinUia.RegressionTests
}
}
Console.WriteLine("RESULT total={0} passed={1} failed={2}", tests.Count, passed, tests.Count - passed);
+ // 退出码约定:0 = 全部通过,1 = 存在失败(供 CI / 脚本判断)。
return passed == tests.Count ? 0 : 1;
}
}
+ // Check —— 断言助手:所有用例统一用它抛 InvalidOperationException 表示失败,
+ // 失败信息里带上用例内传入的 message,便于定位。
internal static class Check
{
+ // 条件必须为真;否则以 message 抛异常。
public static void True(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
+ // 断言值相等(用默认相等比较器);失败时附带 expected/actual。
public static void Equal(T expected, T actual, string message)
{
True(EqualityComparer.Default.Equals(expected, actual),
message + "; expected=" + expected + "; actual=" + actual);
}
+ // 断言引用相同(节点必须还是原来那个对象,防止树刷新时被重建)。
public static void Same(object expected, object actual, string message)
{
True(ReferenceEquals(expected, actual), message + "; node reference mismatch");
}
+ // 断言 path 在 root 上按顺序解析到给定节点;唯一命中时额外校验 SelectUnique 也一致。
public static void Matches(ControlTreeNode root, string path, params ControlTreeNode[] expected)
{
string error;
@@ -72,6 +112,7 @@ namespace PacsWinUia.RegressionTests
}
}
+ // 断言 path 被拒绝:Select 返回空、SelectUnique 返回 null,且都带非空错误信息。
public static void Rejected(ControlTreeNode root, string path)
{
string error;
@@ -82,6 +123,7 @@ namespace PacsWinUia.RegressionTests
}
}
+ // 每个持久化用例独占一个临时目录,Dispose 时递归删除;不碰真实用户配置目录。
internal sealed class TemporaryDirectory : IDisposable
{
public TemporaryDirectory()
@@ -96,6 +138,16 @@ namespace PacsWinUia.RegressionTests
}
// Every node is an in-memory snapshot: no AutomationElement, HWND lookup, GUI or provider calls.
+ //
+ // TreeFixture —— 供 XPath 用例复用的纯内存控件树夹具,结构:
+ // Window(设置, RootClass)
+ // ├─ Custom(PermanentNavigationView)
+ // │ ├─ Group(...BreadcrumbBar) > Button(个性化) > Text(个性化) → BreadcrumbText
+ // │ └─ Window(PaneRoot) > Pane(MenuItemsScrollViewer) > Group(MenuItemsHost)
+ // │ └─ ListItem(个性化) → MenuItem
+ // ├─ Group(Duplicates):重复 AutomationId、同名异类型、有无 Id、无名字等边界节点
+ // └─ Text/Edit:中文、单双引号、斜杠、> < & [ ] 等转义样本
+ // Node(...) 造节点、Add(...) 挂子节点、All(...) 深度优先枚举,供 roundtrip/改名校验遍历全树。
internal sealed class TreeFixture
{
public const string BreadcrumbLegacy = "[Uia] Custom[PermanentNavigationView] > Group[PermanentNavigationViewBreadcrumbBar] > Button:个性化 > Text:个性化";
diff --git a/tests/regression/RegressionTests.csproj b/tests/regression/RegressionTests.csproj
index 893ae55..1522928 100644
--- a/tests/regression/RegressionTests.csproj
+++ b/tests/regression/RegressionTests.csproj
@@ -1,4 +1,13 @@
+
Debug
@@ -21,6 +30,7 @@
+
{C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}
@@ -35,6 +45,7 @@
+
ControlTreeReconciler.cs
diff --git a/tests/regression/SettingsComboBoxTests.cs b/tests/regression/SettingsComboBoxTests.cs
index b545da2..9c0af29 100644
--- a/tests/regression/SettingsComboBoxTests.cs
+++ b/tests/regression/SettingsComboBoxTests.cs
@@ -1,3 +1,18 @@
+// =====================================================================================
+// SettingsComboBoxTests —— 设置页悬浮条「进程/类名/标题」下拉的原生选择回归。
+//
+// 覆盖范围:用真实的 Win32 消息(鼠标点击列表项 + 关闭下拉、方向键选择)驱动下拉,
+// 断言 CBN_SELENDOK/SELCHANGE/CLOSEUP 之后原生 EDIT 文本与 ComboBox.Text 一致,
+// 并且刷新建议列表 / 切换悬浮条 / 手动输入后选值仍然保留;最后 Save+Load 校验持久化。
+//
+// 为什么这样测:这是 WinForms 自身控件与其 Win32 子窗口(Edit/List)之间的同步问题,
+// 只能靠真实的消息循环验证;用例运行在 Program.Main 的 STA 线程上,所有 HWND 消息
+// 只发给本用例自己创建的控件,不涉及 UIA、真实目标窗口枚举、SendInput 或杀进程。
+// 截图仅在设置了 PACS_REGRESSION_SCREENSHOTS 环境变量时写出(失败时也有留存)。
+//
+// 新增用例:加到 Register(...) 列表并实现 private static void 方法,断言走 Check.*;
+// 私有成员通过反射访问(Field/PrivateCombo/InvokePrivate)。
+// =====================================================================================
using System;
using System.Collections.Generic;
using System.Drawing;
@@ -19,6 +34,8 @@ namespace PacsWinUia.RegressionTests
{
public static void Register(IList> tests)
{
+ // 防:原生选择后 ComboBox.Text 与 EDIT 文本不同步(经典“显示回退成上一个值”)、
+ // 刷新或手动输入丢值、以及保存后进程/类名/标题未持久化。
tests.Add(new KeyValuePair(
"Floating suggestions native mouse/keyboard selection, refresh and persistence",
SelectionRefreshAndPersistence));
diff --git a/tests/regression/TreeRefreshTests.cs b/tests/regression/TreeRefreshTests.cs
index f87ec33..6574ae3 100644
--- a/tests/regression/TreeRefreshTests.cs
+++ b/tests/regression/TreeRefreshTests.cs
@@ -1,3 +1,15 @@
+// =====================================================================================
+// TreeRefreshTests —— 控件树增量刷新(ControlTreeReconciler)的节点身份保持回归。
+//
+// 覆盖范围:在同一棵 System.Windows.Forms.TreeView 上反复 Apply(fresh) 时,
+// 未变化的节点必须复用原 TreeNode(句柄、选中、展开状态不丢),只有真正新增/
+// 删除/移动的节点才变更;RuntimeId 缺失时的回退身份不得依赖可变的 Name。
+//
+// 为什么这样测:用本进程自建的 TreeView 与内存快照对拍,不调用 UIA、不枚举真实窗口。
+// 这里跑的是 WinForms 自身控件(安全),危险的是 UIA 自读——两者不要混淆。
+//
+// 新增用例:加到 Register(...) 列表并实现 private static void 方法,断言走 Check.*。
+// =====================================================================================
using System;
using System.Collections.Generic;
using System.Windows.Forms;
@@ -10,8 +22,11 @@ namespace PacsWinUia.RegressionTests
{
public static void Register(IList> tests)
{
+ // 防:静置或仅改名时整树被重建,导致句柄/选中/展开状态丢失、Tag 未重绑。
tests.Add(new KeyValuePair("Tree refresh retains native items when unchanged or renamed", RetainsItems));
+ // 防:结构调整时误重建根节点,移动/重挂的节点丢失身份,选中与展开状态被清。
tests.Add(new KeyValuePair("Tree refresh applies only insert, remove and move differences", StructuralChanges));
+ // 防:无 RuntimeId 时的回退身份依赖可变的 Name,改名即被当成新节点。
tests.Add(new KeyValuePair("Tree fallback identity ignores mutable Name", FallbackIdentity));
}
diff --git a/tests/regression/WindowVisibilityTests.cs b/tests/regression/WindowVisibilityTests.cs
index 01b8d3f..53993cb 100644
--- a/tests/regression/WindowVisibilityTests.cs
+++ b/tests/regression/WindowVisibilityTests.cs
@@ -1,3 +1,17 @@
+// =====================================================================================
+// WindowVisibilityTests —— 悬浮条遮挡诊断的窗口归属判断回归。
+//
+// 覆盖范围:WindowVisibility.IsOwnProcessWindow 对零句柄/本进程窗体/外部窗口的分类,
+// 以及 DescribeOccluders 生成的遮挡说明——本工具自己的窗口必须被单列为“本工具窗口/
+// 设置页自检”,外部窗口则只能被称作普通遮挡,绝不能反过来把遮挡归咎于本工具。
+//
+// 为什么这样测:只用本测试进程自建的 WinForms 窗体句柄与手工构造的 IntPtr 列表;
+// WindowEnumerationResult 天然排除本进程,所以它返回的窗口一定属于外部进程。
+// 不调用 UIA、也不操作真实目标窗口。外部窗口很可能不存在(由外部环境决定),
+// 因此相关断言在无外部窗口时会打印提示并跳过,属于预期内的“部分跳过”。
+//
+// 新增用例:加到 Register(...) 列表并实现 private static void 方法,断言走 Check.*。
+// =====================================================================================
using System;
using System.Collections.Generic;
using System.Windows.Forms;
@@ -16,7 +30,9 @@ namespace PacsWinUia.RegressionTests
{
public static void Register(IList> tests)
{
+ // 防:本工具自身窗口被误判为外部遮挡窗口(或外部窗口被误判为本进程)。
tests.Add(new KeyValuePair("Own-process detection classifies tool windows", OwnProcess));
+ // 防:遮挡提示把外部窗口也算作本工具窗口,或本工具窗口不被单独说明。
tests.Add(new KeyValuePair("Occluder message names the blocker and never blames the tool wrongly", OccluderMessages));
}
diff --git a/tests/run-fixture.cmd b/tests/run-fixture.cmd
index 4524e41..6171d98 100644
--- a/tests/run-fixture.cmd
+++ b/tests/run-fixture.cmd
@@ -2,11 +2,13 @@
rem 构建并启动 UIA 测试夹具(一个普通的 WinForms 窗口,用来验证控件树/拾取/列表读取)。
rem 需要 .NET Framework 4.8(Windows 自带)与 dotnet SDK 或 MSBuild。
setlocal
+rem HERE = 本脚本所在目录;PROJECT = 夹具工程;CONFIG 取第一个参数,缺省 Debug。
set HERE=%~dp0
set PROJECT=%HERE%uia-fixture\UiaFixture.csproj
set CONFIG=%1
if "%CONFIG%"=="" set CONFIG=Debug
+rem 优先用 dotnet msbuild;找不到 dotnet 时回退到独立安装的 MSBuild。
where dotnet >nul 2>nul
if %ERRORLEVEL%==0 (
dotnet msbuild "%PROJECT%" -p:Configuration=%CONFIG% -v:m -nologo
@@ -18,5 +20,6 @@ if not %ERRORLEVEL%==0 (
exit /b %ERRORLEVEL%
)
+rem 构建成功后用 start 以独立进程启动夹具窗口(不阻塞脚本)。
start "" "%HERE%uia-fixture\bin\%CONFIG%\UiaFixture.exe"
endlocal
diff --git a/tests/uia-fixture/FixtureForm.cs b/tests/uia-fixture/FixtureForm.cs
index dbaf275..9c5c9d2 100644
--- a/tests/uia-fixture/FixtureForm.cs
+++ b/tests/uia-fixture/FixtureForm.cs
@@ -1,3 +1,17 @@
+// =====================================================================================
+// UiaFixture —— 跨进程验证用的真实 WinForms 夹具(单独的可执行程序)。
+//
+// 为什么必须是独立进程:本工具靠 UIA 读取“别的进程”的控件树,而 UIA 在**同一进程内**
+// 自读自己的控件树会崩溃(见 MEMORY:in-process UIA self-reads segfault)。
+// 因此需要一个真正独立的进程暴露一棵已知且稳定的控件树,让工具跨进程去读、去拾取、
+// 去按 path 定位——这样测的才是生产路径。夹具自身不做任何 UIA 调用。
+//
+// 这棵树的控件类型/名称/AutomationId 都固定,且窗口标题与类名在多次运行间保持不变,
+// 所以保存的监控条目、悬浮条显示条件可以长期复用它。
+//
+// 打开方式:tests\run-fixture.cmd(或用 Rider/VS 直接跑本项目)→ 工具里
+// 刷新窗口 → 选中「UIA 测试夹具」→ 检查选中窗口;验证清单见 tests\README.md。
+// =====================================================================================
using System;
using System.Drawing;
using System.Windows.Forms;
diff --git a/tests/uia-fixture/UiaFixture.csproj b/tests/uia-fixture/UiaFixture.csproj
index a965a18..e2c6ab5 100644
--- a/tests/uia-fixture/UiaFixture.csproj
+++ b/tests/uia-fixture/UiaFixture.csproj
@@ -1,4 +1,10 @@
+
Debug