commit b4c736d58b93a8e9d4e7f5cbefe614037bd584fb Author: zimoyin Date: Mon Oct 12 14:33:49 2026 +0800 基线提交:三来源控件树/拾取 + 无界面读取 + 设置框架 在继续做界面收敛与监控引擎之前先固化当前可编译、可运行的状态,便于回退。 已完成: - 控件树与拾取支持三种来源:UIA / MSAA(oleacc) / Win32(EnumChildWindows),可下拉切换与自动降级 - 列表读取:祖先链 + 向下查找 + 子元素遍历降级;区分「没找到」与「找到但取不到值」 - 无界面读取:--read-config / --read-saved,输出 JSON(含逐步 resolution 诊断) - 监控列表:结构化定位字段(进程/窗口类/标题关键词/UIA 路径/MSAA PathKey/Win32 类名+序号) - 设置框架:settings.json(随输出目录拷贝,不嵌入 exe)+ 设置界面 + 命令生命周期钩子 + 悬浮按钮 - 控制台日志、布局自检、控件树搜索、窗口列表前台高亮 已知未实现:OCR(仅配置占位)、截图、监控引擎(事件监听)。 Co-Authored-By: Claude Code diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8c6b36e --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +bin/ +obj/ +/packages/ +riderModule.iml +/_ReSharper.Caches/ +.idea/ +.vs/ +*.user +*.suo +*.DotSettings.user +TestResults/ diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..72aabdc --- /dev/null +++ b/TODO.md @@ -0,0 +1,301 @@ +# TODO + +> 当前代码按阶段开发;未在目标 Windows/PACS 环境实测的能力不得标记为已完成。项目源码位于 `src/pacs_win_uia`,Rider 入口为根目录 `pacs_win_uia.sln`。 + +## 当前阶段:项目基础架构、窗口枚举、UIA 检查与控件树 + +- [x] 使用 MSBuild 完成 Debug 与 Release 的完整编译(当前环境已使用 `dotnet msbuild` 验证) +- [x] 将源码整理到 Rider 可见的 `src/pacs_win_uia` 目录,并更新 `pacs_win_uia.sln` +- [x] 添加基础应用程序清单,声明 Windows 7/10/11 兼容性与基础 DPI 感知策略(Per-Monitor DPI 仍需目标系统验证) +- [x] 补充 Windows 10/11 supportedOS 清单 GUID +- [x] 实现十字拾取器基础流程:Esc 取消、鼠标释放确认、工具自身窗口排除、非激活高亮 +- [x] 拾取覆盖层改为点击穿透并使用 Win32 光标轮询,避免把覆盖层自身当作目标 +- [x] 将十字拾取器的 Win32 坐标与 UIA `System.Windows.Point` 坐标统一(多显示器负坐标仍需实机验证) +- [x] 限制拾取预览为单个并发探测,并合并最新坐标,避免鼠标移动造成无限 UIA 任务堆积 +- [x] 探测任务发生异常时观察并终止当前拾取确认重试,避免故障 Provider 无限重试 +- [x] 拾取初次显示前同步标记原生覆盖层可见状态,避免初始 WindowFromPoint 自命中 +- [x] 覆盖层首次显示使用 `SW_SHOWNOACTIVATE`,降低初始探测时的焦点变化 +- [x] 鼠标释放确认前重新解析当前底层 HWND,避免静止光标下接受旧控件缓存 +- [ ] 进一步验证覆盖层显示/隐藏与前台窗口交互,确保目标焦点不被改变 +- [x] 成功拾取后清除旧高亮;无效目标不触发 `Picked` +- [x] 拾取异常/取消路径清理当前确认状态并关闭高亮 +- [x] 释放确认前清空旧探测结果,必须取得当前坐标的新探测 +- [x] 拾取确认不再在 UI 线程同步调用 UIA;当前坐标没有完成预览时明确返回未确认结果 +- [ ] 验证十字拾取器不抢占目标焦点,并在 Windows 7/10/11 与高 DPI 多屏环境手工验收 +- [ ] 记录并尽可能恢复拾取前的前台窗口/焦点;当前实现不保证完全无感恢复 +- [x] 修复拾取覆盖层命中问题:覆盖层短暂隐藏解析底层 HWND,确认点击仍由覆盖层接收 +- [x] 增加覆盖层 MouseDown/MouseUp 确认路径,降低极短鼠标点击被 40ms 轮询漏掉的概率 +- [ ] 验证极短鼠标点击/极短 Esc 按键不会因 40ms 轮询而丢失 +- [ ] 处理跨进程 UIA Provider 同步调用无法被强制终止的限制;必要时迁移到独立辅助进程 +- [x] 使树读取任务在窗口切换时通过独立 CancellationTokenSource 发起取消(同步卡住的 Provider 仍可能无法立即退出) +- [x] 在窗口/控件切换和窗体关闭时使旧树读取结果失效 +- [x] 拾取新目标时使旧窗口检查任务失效 +- [x] 拾取新目标时重置控件树导出按钮和检查按钮状态 +- [x] 释放确认使用同一屏幕坐标解析 HWND,避免 Cursor.Position 二次读取漂移 +- [x] 树读取完成回调增加窗口句柄/序号和窗体句柄销毁保护 +- [x] ControlType 属性读取加入逐项异常捕获 +- [x] 深度限制下真实叶节点不再误标记为不完整 +- [ ] 为 UIA 属性逐项错误、Pattern 枚举和控件树部分失败补充自动化测试 +- [x] 减少每个控件重复 Pattern 探测:优先使用 `GetSupportedPatterns()`,仅在无结果时回退查询 +- [ ] 清理快照中的长期 `AutomationElement` 引用;导出/显示模型应优先只保留可序列化快照 +- [x] 列表读取前重新按 HWND/RuntimeId 绑定当前 UIA 元素,避免复用失效代理(先在降级抢救路径上按 HWND 重新绑定;常规路径仍复用拾取时的元素) +- [ ] 高亮框改为经过实机验证的跨进程点击穿透窗口 +- [x] 拾取结果对 Win32/UIA 进程 ID 做一致性检查,拒绝跨进程目标拼接 +- [x] 已知 HWND 的拾取使用该窗口 UIA 树内的坐标元素解析,减少同进程弹窗错配 +- [x] 窗口内坐标拾取使用全局节点预算,避免递归分支重复消耗上限 +- [x] 在窗口/控件切换时清理旧列表结果并使进行中的列表读取失效 +- [ ] 在控件失效后按 HWND/RuntimeId 重新绑定 UIA 元素,而不是跨线程长期复用原代理 +- [ ] 增加窗口枚举、模型、控件树限制和 JSON 导出的自动化测试 +- [x] 修复窗口列表无选中项时清理旧树、旧元素和旧导出状态 +- [x] 修复拾取按钮首次启动不可用问题 +- [ ] 为窗口刷新改为后台快照或先做廉价可见性/PID 过滤,避免阻塞 WinForms UI +- [x] 窗口枚举使用明确结果对象,保留 EnumWindows 失败状态 +- [ ] 增加独立的 Windows UIA 测试夹具(按钮、文本框、树和列表) +- [ ] 在 Windows 7 SP1、Windows 10、Windows 11 实机验证窗口枚举和 UIA 能力 +- [ ] 验证普通权限访问高权限目标时的明确降级状态,不绕过 UIPI +- [x] 修正窗口样式辅助 API 的 64 位入口声明(实际调用仍需目标系统验证) +- [ ] 验证 32 位/64 位目标进程、100%/125%/150%/200% DPI、多显示器与 RDP 场景 +- [ ] 为 JSON 导出增加敏感数据提示、脱敏策略和导出来源/时间记录 +- [ ] 编写第一阶段用户操作手册和验收记录 + +## 第二阶段:列表控件读取 + +- [x] 设计统一列表读取结果模型(来源、时间、完整性、可信状态和错误) +- [x] 实现 UIA `GridPattern` 和 `TablePattern` 的只读单元格读取(`ListReaderService`) +- [x] 实现 `SelectionPattern` 的只读选中项读取基础版(选择-only 控件也会返回选中项结果) +- [x] 补充 ValuePattern/TextPattern/Name 的值来源状态,并区分“元素存在但未暴露值”与真实空字符串 +- [x] 在主界面增加“读取选中控件列表”入口,并显示总行列、已读行/单元格、错误数和选中项数量 +- [x] 列表单元格不再吞掉取消/超时异常;Value/Text/Name 读取失败会保留单元格错误状态 +- [x] 失败单元格也保留 RowId/ColumnId,便于诊断和导出定位 +- [x] 取消/超时返回时保留已经读取的行列,并在最终成功前再次检查软截止时间(同步 UIA Provider 调用仍只能软超时) +- [x] 保持 Grid/Table 读取的累积结果对象,使超时/取消结果保留已读取的来源、行数和单元格 +- [x] 取消/超时异常在读取器入口使用累积结果处理,不丢失已读取行列 +- [x] 行对象在首个单元格读取前加入结果,保留取消/超时时的当前行部分数据 +- [x] 选中项读取失败后重新计算最终状态,避免 `Success` 与 `IsComplete=false` 矛盾 +- [x] SelectionPattern Provider 异常降级为部分结果,不覆盖已读取的表格数据 +- [x] 选中项结果增加 RowId 字段(当前优先使用 AutomationId,完整行映射仍需目标控件验证) +- [ ] 补充 SelectionItem 行/单元格映射和当前选中项模型 +- [ ] 为 DataGridView 结果面板添加列名映射及单元格错误详情展开 +- [x] 实现 UIA 子元素遍历降级并区分可见数据与完整数据(见「本轮修复」一节) +- [x] TablePattern 失效时尝试回退 GridPattern(Provider 行为仍需实测) +- [ ] 评估 Win32 ListView/ListBox/TreeView 消息读取 +- [ ] 评估 MSAA/IAccessible 降级 +- [ ] 支持读取列名、可见行、当前单元格和全部可访问行 +- [ ] 为大表格增加单元格预算/分页策略,避免一次性物化过大的二维结果 +- [x] 导出 CSV 时限制 provider 声明的异常大列数,避免生成超大空字段(当前上限 10000 列) +- [x] CSV 稀疏单元格按 ColumnIndex 计算列数,避免高索引列被静默丢弃 +- [x] CSV 对公式样式值增加文本前缀,避免电子表格执行导出内容 +- [x] CSV 导出补充逐行/逐单元格错误、ValueSource、选中项和读取时间等完整元数据 +- [x] 添加独立列表 JSON/CSV 导出服务(`ListResultExporter`) +- [x] 在主界面接入列表 JSON/CSV 导出、用户确认和敏感数据提示 +- [x] 导出格式以保存对话框 FilterIndex 为准,并自动规范化扩展名 +- [ ] 输出列表 JSON 与 CSV 的脱敏版本,并记录导出来源/时间 +- [x] 增加列表读取器的 UI 结果面板,显示已读取行和单元格状态 +- [x] 读取结果面板显示不可用单元格的错误文本占位 +- [x] 使用 DataTable 显示列表列名和单元格值,避免 DataGridView 直接绑定字典 +- [x] DataTable 列数设置上限并处理重复列名,避免异常 Provider 导致 UI 崩溃 +- [x] 新拾取开始时隐藏上一目标高亮 +- [x] 切换窗口或控件时清空旧列表结果表格 +- [x] 单元格 ValuePattern/TextPattern 访问的取消和超时异常继续向读取器传播 +- [x] ValuePattern/TextPattern 普通 Provider 异常会回退到下一种只读值来源 +- [ ] 增加结果面板的列名、错误详情和选中项专用视图 +- [ ] 增加 PACS 真实列表手工验收,禁止把屏幕文字直接当作完整数据源 + +### 本轮修复(拾取隐藏、控件树、界面、监控列表、列表读取降级、日志) + +- [x] 拾取时隐藏主界面,拾取完成后恢复并把前台窗口交还给原窗口(避免抢焦点) +- [x] 拾取完成后以被拾取元素为根自动读取并显示控件树,并切到「控件树」页 +- [x] 窗口列表选中项变化后自动读取控件树(350ms 防抖 + 按 HWND 去重 + 单飞),保留「检查选中窗口」手动入口 +- [x] 窗口列表加入分组分割线与搜索(标题 / 进程名 / PID),“有标题且可见”的窗口排在主要窗口组 +- [x] 主界面按屏幕工作区自适应(工作区小于期望尺寸时最大化),右侧属性区放入横向滚动宿主 +- [x] 右侧属性网格下方新增「控件监控列表」编辑器:控件Path、RuntimeId、所在页面特征、内容Key,可增删改并保存为 JSON +- [x] 控件监控定义校验规则集中到 `ControlMonitorRules`,一次返回全部问题;保存前会 `EndEdit` 并显示逐行错误 +- [x] 控制台日志(`AppLog`):纯 GUI 启动时自建控制台窗口,终端/IDE 管道启动时复用现有标准输出,关闭控制台不会终止程序 +- [x] 列表读取改为「被拾取元素 + 上级元素」候选链:先找 GridPattern/TablePattern,找不到再降级为子元素遍历 +- [x] 候选链不会越过顶层窗口,并且绝不会探测或下钻桌面元素(否则会枚举全机器窗口) +- [x] 新增 `Notices`(降级提示与 `Errors` 分离)与 `TotalRowsKnown`(区分“逻辑总行数”和“当前已实现行数”) +- [x] 遍历降级按来源区分取值顺序:编辑类单元格优先 ValuePattern(其 Name 是标签而非内容),其余优先 Name +- [x] 跳过行头/表头/滚动条等非数据单元格,避免列错位;整行只有表头单元格时视为表头带而不是数据行 +- [x] GridPattern/TablePattern 能读到行列但单元格全部失败时,改用子元素遍历抢救单元格值,并按 HWND 重新绑定元素 +- [x] 连续 10 个单元格读取失败即停止继续调用(避免把已崩坏的 Provider 打爆),并明确提示“无法取值 ≠ 列表为空” +- [x] 新增**向下查找**:拾取到整个窗口/页面容器时(列表在被拾取元素内部),在被拾取元素内 BFS 最多 4 层、600 个节点寻找列表(含无 Pattern 的行容器遍历降级) +- [x] 所有 Pattern 搜索(向上 + 向下)都排在所有遍历降级之前:窗口的布局面板在形状上“也像行”,遍历若先跑就会返回假列表并挡住真正的 Grid/Table +- [x] 遍历结果里“读不到值的行”超过一半时判定为布局容器而不是列表,不再把窗口面板当成行 +- [x] 列表读取未成功时自动打印被拾取元素及上级的结构诊断(ControlType/Class/框架/PID/支持的 Pattern/子元素),控件树只有根节点时也明确提示“该元素没有暴露任何 UIA 子元素” +- [x] 修复界面区域丢失:重构右侧时遗漏了中间栏,导致「控件树/列表结果」标签页从未加入窗体、界面上完全看不到。现为三栏:窗口列表 | 控件树/列表结果 | 属性 + 控件监控列表 +- [x] 新增启动时布局自检:列出每个关键区域,任何一个没有被加入窗体都直接记为错误(避免"代码写了但界面没有"这类静默缺陷) +- [x] 控件树只有根节点时,400ms 后自动重试一次:Chromium/CEF/Electron/WebView2 的无障碍树是按需激活的,首次查询常常只返回根节点 +- [ ] 以上向下查找、容器判定与无障碍激活重试仍需要在真实 PACS(OCS)上复测;OCS 窗口的 UIA 暴露情况见下 + +#### 第二轮现场反馈修复 + +- [x] 修复拾取器点左键后不关闭:UIA 探测挂住时拾取会永远停留。现在点击有 1.2 秒硬期限,超时按 **Win32 窗口信息**确认目标(该路径无 UIA 调用,不会挂),无论如何都会关闭覆盖层并恢复界面 +- [x] 拾取看门狗不再清掉待确认的点击(此前会把用户已经按下的左键请求丢弃) +- [x] 拾取探测改到独立线程(`LongRunning`),卡死的 Provider 不再占用线程池 +- [x] 拾取只拿到顶层窗口时(浏览器内核/套壳应用首次查询往往如此),600ms 后按同一坐标**自动重探一次**,拿到更深的元素就改用该元素 +- [x] 列表遍历不再把"控件类元素"当容器:Button / Edit / Text / CheckBox / ComboBox / MenuItem / TabItem / Slider / ProgressBar / Header / ScrollBar 等一律跳过(这正是"向上第 1 级的 ControlType.Button"假结果的来源) +- [x] 遍历结果只有 1 行 1 列时判定为"不是列表",改为如实报告未找到(不再把单个控件的内容当成列表) +- [x] 结构诊断改为只要结果来自遍历降级或行列数 ≤1 就打印,不再只在 Unsupported/Failed 时打印 +- [x] 主界面尺寸按屏幕比例自适应:小屏不超屏、大屏不再过小(本机 2560x1528 → 2048x1298,此前固定 1400x850) +- [x] 右侧新增「控件摘要」:类型 / 名称 / AutomationId / 类名 / 框架 / PID / HWND / 支持的模式 / **控件 Path**(Path 在后台线程生成,不阻塞界面) +- [x] 右侧分栏比例调整(属性网格 52% / 控件监控列表 48%),属性网格最小内容宽度从 460 降到 360,避免属性值被横向滚动条推到看不见的位置 +- [x] 拾取后窗口列表按**顶层窗口 HWND** 同步选中(此前拾取到子窗口时列表没有对应行,所以看起来"没有同步") + +#### 第三轮现场反馈修复(截图定位) + +- [x] 修复「控件监控列表」只有 150x150:UserControl 加入面板时没有设置 `Dock=Fill`,一直是默认尺寸,所以列显示不全、"大小特别小" +- [x] 布局自检增加**尺寸检查**:列出每个区域的实际尺寸,小于预期就报错(只检查父级关系查不出"已加入窗体但仍是默认 150x150"这类问题) +- [x] 属性网格下方的说明栏(此前只重复属性名,被判为"毫无作用")改为显示**字段含义**:为 `UiaElementInfo` 逐属性补 `[Description]`,说明该字段是什么、为空意味着什么、以及排查时的注意点 +- [x] UIA Pattern 名称规范化:`TransformPatternIdentifiers.Pattern` 这类原始名统一显示为 `TransformPattern`,并补充 Transform/ScrollItem/Toggle/RangeValue/MultipleView 到已知模式表 +- [x] 监控列表列宽调整(控件Path 权重 50、RuntimeId 110、页面特征 35、内容Key 130),窄栏时 Path 不再被挤没 +- [x] 本机验证:屏幕 2560x1528 → 主界面 2048x1298;窗口列表 474x1088、控件树 717x1102、属性网格 783x491、控件监控列表 783x535;布局自检"异常区域 0 个" + +#### OCS 客户端的实测结论(截图 + 日志已确认) + +- 目标窗口 `OCS - 浏览器列表` 的 `ClassName = Chrome_WidgetWin_1`、`FrameworkId = Win32`、`PID = 24368`,控件树**只有根节点**,`SupportedPatterns` 只有 `WindowPattern / TransformPattern`。即:这是 **Chromium/CEF 套壳应用,且没有开启无障碍支持**,UIA 完全看不到里面的渲染内容(拾取、控件树、列表读取都只能拿到窗口本身),400ms 激活重试也无效 +- [ ] 用微软 `Inspect.exe` / Accessibility Insights 对同一个窗口做交叉验证:若它们同样只能看到窗口,则确认是目标程序未暴露,而不是本工具的问题 +- [ ] 对这类客户端评估非 UIA 路线(Win32 消息 / OCR / 图像识别),并在 README 中明确标注该限制,不允许把"读不到"包装成"读到了空列表" + +#### 第四轮:控件树与拾取改为三来源(UIA + MSAA + Win32) + +- [x] 新增统一节点模型 `ControlTreeNode`(组合 `UiaElementInfo` / `MsaaNodeInfo` / `NativeWindowInfo`,每节点带来源标记) +- [x] 新增 **Win32 树**(`Win32TreeReader`):一次 `EnumChildWindows` 拿全部后代,按 `GA_PARENT` 重建层级,`GetWindowInfo` 一次拿窗口/客户区矩形与样式;标题走 `SendMessageTimeout(WM_GETTEXT, SMTO_ABORTIFHUNG)`,隐藏窗口不取标题;过滤 message-only 与 DWM cloaked 窗口 +- [x] 新增 **MSAA 树**(`MsaaService` + `MsaaTreeReader`):用框架自带 `Accessibility.IAccessible`(不手写 vtable),`AccessibleObjectFromWindow(OBJID_CLIENT)` 失败回退 `OBJID_WINDOW`,`AccessibleChildren` 分批读取并按运行时类型分派"简单子 ID / 子对象",每个对象读完立即 `ReleaseComObject` +- [x] 工具条新增「控件树来源」下拉框(自动 / UIA / MSAA / Win32,默认自动)与「尝试激活目标无障碍」实验按钮(默认不自动启用) +- [x] 自动模式按 UIA → MSAA → Win32 取第一个**有内容**的来源(只有根节点视为没内容),并在状态栏说明实际用了哪个来源 +- [x] 拾取改为三来源:Win32(`WindowFromPoint` + `ChildWindowFromPointEx` 逐级下钻,每级 `ScreenToClient`)→ UIA → MSAA;非 UIA 目标也能高亮(统一用 `Bounds`) +- [x] MSAA 拾取改为在**已下钻到的最深窗口上做 `accHitTest`**(实测:全局 `AccessibleObjectFromPoint` 只返回顶层窗口对象,而在 ListView 窗口上 `accHitTest` 直接返回"列表"角色与其真实矩形) +- [x] 窗口标题读取全部改为 `SendMessageTimeout`:`GetWindowText` 是跨进程 `WM_GETTEXT`,会让窗口刷新卡住 +- [x] `UiAutomationService` 的私有 `TreeReadState` 抽成共享的 `ReadBudget`,三个读取器统一受"深度 / 节点数 / 截止时间 / 取消"约束 +- [x] 本机自检(独立宿主进程)实测:UIA 56 节点、MSAA 167 节点(中文角色名)、Win32 7 个原生窗口且**包含 ListView 句柄**;自动模式正确选中 UIA;拾取下钻到 `WindowsForms10.SysListView32` 子窗口 +- [ ] 在真实 PACS / OCS 上分别切三个来源复测;对 OCS 点一次「尝试激活目标无障碍」看 UIA 是否出现内容 + +#### 三来源的边界(必须同时写进文档与界面) + +- 可靠:选定根窗口的**每个后代 HWND 都会出现在 Win32 树里**(HWND / 类名 / 窗口矩形 / 客户区矩形) +- 尽力而为:窗口标题(跨进程、UIPI 或目标无响应时为空)、以及任何控件内容(取决于目标是否提供 UIA / MSAA) +- 做不到:`asInvoker`(中完整性)读不到提权进程;GPU/自绘且无提供者的界面三来源都看不到;MSAA 对列表的保真度低于 UIA(`SysListView32` 行一般是简单子 ID,通常只有第一列文本) +- 三个来源是独立视图,**不保证互相对应**,跨进程一律不合并 +- 本轮不改 DPI 感知(仍 system aware):混合 DPI 下 Win32 矩形与 UIA 矩形可能不一致,单屏不受影响;PerMonitorV2 需要单独一轮 + +#### 第五轮:拾取标记修复 + valueKey/value + 无界面读取(CLI/JSON) + +- [x] **修复拾取标记不准**:UIA 只返回顶层窗口时,之前会用 UIA 元素的矩形覆盖高亮框,于是框住整个窗口。现在只在矩形**更小**时才替换(实测:在列表行上拾取,Bounds 从 860x560 的窗口变成 1266x285 的列表) +- [x] UIA 只拿到窗口本身时不再停止:继续在已下钻到的最深窗口上做 MSAA `accHitTest`;两者都没有时新增 `IsWindowOnlyPick`,状态栏明确写"只拾取到窗口(UIA/MSAA 都没有暴露内部控件),不要以为工具坏了" +- [x] 拾取下钻去掉 `CWP_SKIPTRANSPARENT`(DirectUIHWND 这类透明样式窗口正是内容宿主),并把下钻链(逐级 HWND)写进日志 +- [x] 修复 MSAA 可能**重复释放同一个 COM 对象**(`accHitTest` 可能返回与根对象相同的实例,二次 `ReleaseComObject` 会导致访问违例) +- [x] `EnumChildWindows` 返回 0 个句柄不再误报为"失败",改为"该窗口没有子窗口"(OCS 就是这种情况) +- [x] 控件树不完整的占位原因 `DescendantIncomplete` 改为显示**第一个具体原因**(达到深度上限/节点上限/超时/取消/读取失败) +- [x] 监控列表新增 **valueKey / value 两列**:valueKey 为可编辑下拉框(按来源预置可用键,也允许手填),value 预填添加时的当前值 +- [x] 监控列表新增「来源」列(自动/UIA/MSAA/Win32),并把定位详情(进程/窗口类/UIA 路径/MSAA PathKey/Win32 路径/RuntimeId)显示在下方说明栏,避免 7 列挤在一起 +- [x] 「添加当前控件」按**当前节点来源**填充:定位字段 + valueKey 默认值 + value(UIA→Name,MSAA→accName,Win32→窗口标题);MSAA/Win32 拾取结果同样可以加入监控列表 +- [x] 监控配置新增结构化定位字段(进程名/窗口类/标题关键词/UIA 路径段/MSAA PathKey/Win32 类名+序号/valueKey/value),**老文件仍可读**(全部为可空新增字段) +- [x] **枚举持久化为可读字符串**(`"Source": "Win32"`):DataContractJsonSerializer 默认把枚举写成数字,手写配置会因 `"Win32"` 解析失败而被判为无效文件(这个 bug 是被无界面模式当场发现的) +- [x] **新增无界面读取**:`pacs_win_uia.exe --read-config <配置> [--output ] [--timeout 10] [--activate] [--help]`,无参数时行为完全不变;退出码 0=全部命中 / 1=有未命中或取不到值 / 2=参数或配置错误 +- [x] 无界面返回 JSON 含每条的:found / resolvedSource / valueKey / value / valueAvailable / attributes / **resolution 逐步诊断** / error / elapsedMs,以及本次可见窗口列表与汇总 +- [x] 空路径 = "顶层窗口本身"(可监控窗口标题/类名/可见性);**回退来源只定位到窗口本身时不算命中**,避免把"没找到控件"报成成功 +- [x] 实测(本机 Notepad,真实跨进程):窗口按 进程名+类名 匹配成功;`窗口标题` 取到 `*使用教程+常见问题.txt - Notepad`;UIA `ClassName` 取到 `Notepad`;Win32 路径解析到真实子窗口 `NotepadTextBox 0x1309EA`;故意写错的 UIA 路径如实报"第 1 段未匹配"并给出同级元素数量 +- [ ] 用你真实的 PACS 配置跑一次 `--read-config`,确认定位字段与取到的值符合预期 + +#### 第六轮:用一个真实配置暴露出的定位问题(已修) + +- [x] **根因**:保存 UIA 路径时,向上走的过程停在"任何一个带 HWND 的 Window 类型元素"上。UWP(设置/ApplicationFrameHost → `Windows.UI.Core.CoreWindow`)和 XAML 里都存在这类内层窗口元素,于是路径被记录成"相对于内层窗口",而回读时从顶层窗口开始找 → 第 1 段永远匹配不上(实测症状:`第 1 段(Group[...])未匹配:同类元素 0 个`) +- [x] **保存侧修正**:路径改为一律相对**根窗口**记录(`GetAncestor(GA_ROOT)`),经过内层窗口元素时记日志提示 +- [x] **回读侧容错 1**:完整路径失败后,自动改用窗口内的内层窗口元素(带 HWND 的 Window 类型,BFS 限深 4/限 200 节点)作为起点重试 +- [x] **回读侧容错 2**:仍失败时,允许**跳过最多 2 个开头段**,在整个窗口内搜索,且**必须唯一命中**才采用;采用时在 resolution 里明确写出"层级与保存时不同,建议重新添加该控件",绝不静默猜测 +- [x] 实测(你自己保存的那条"设置 → 个性化"配置):`found=true`、`valueKey=Name`、`value="个性化"`、退出码 0,并给出跳过 1 段唯一命中的说明 +- [x] 顺带确认 UWP 的一个事实:设置窗口的 `ApplicationFrameWindow` 属于 `ApplicationFrameHost`(PID 19448),而真正的内容 `Windows.UI.Core.CoreWindow` 属于**另一个进程**(设置自己,PID 21180),其子树是 XAML(`Custom[PermanentNavigationView]` 等)。窗口定位必须用**框架窗口**的进程名+类名(已如此处理),控件路径则由 UIA 跨进程自动接续 +- [x] 控件树的"直接子元素"诊断输出补上 `HWND` 与 `Framework`,这类"内层窗口元素"问题下次一眼可见 +- [ ] 在界面上**重新添加一次**该控件,让保存的路径变成相对根窗口的干净路径(旧路径虽然现在能容错命中,但会多一条提示) + +#### 第七轮:控件树加载慢 / 只读到标题栏 / 无界面默认路径 + +- [x] **定位并修复路径少一层的 bug**:保存 UIA 路径时,向上走到"父级是根窗口"就 break,导致**根窗口的直接子元素没有被记录**——每条路径整体少一层。实测修复后:记事本文本框 → `Pane#0`、第二个 Pane → `Pane#1`,与窗口的真实子元素一致 +- [x] **控件树读取提速**:改用 `CacheRequest`(一次性缓存全部属性与 Pattern)+ 每个父级一次 `FindAll(Children)` 批量取子元素,取代"每个节点一次属性往返 + 每个兄弟一次 GetNextSibling"。56 个节点的窗口:**372~547ms → 187~231ms**;`RuntimeId` 改为按需读取(省掉每节点一次跨进程调用,只在"添加当前控件"时取) +- [x] **"只读到标题栏"的真相**:UWP(设置/计算器)、CEF 套壳应用的内容树是**异步生成**的,窗口刚出现时确实只有边框。现在:① 只读到边框就等 700ms 重读一次(日志写明两次的节点数);② 仍只有边框时自动改读**内层内容窗口**(UWP `CoreWindow` / 浏览器渲染窗口);③ 还是只有边框时状态栏明确说明,而不是把 4 个按钮当成答案 +- [x] 读取期间控件树显示 `正在读取控件树…(来源)` 占位节点,状态栏每 500ms 刷新"已 X.X 秒",不再让"空/只有边框"看起来像读完了 +- [x] 实测:真实"设置"窗口现在一次读到 **114 个节点**(含 `Custom[PermanentNavigationView]` 等 XAML 内容) +- [x] **无界面默认路径**:新增 `--read-saved` = 读取界面保存的配置(`%LocalAppData%\pacs_win_uia\control-monitors.json`)并把结果写到 **exe 同目录的 out.json**(从 `bin\Debug` 运行即 `bin\Debug\out.json`);`--read-config` / `--output` 省略路径时也用同一套默认值;解析出的两个路径打印到 stderr,stdout 保持纯 JSON +- [x] 实测:`pacs_win_uia.exe --read-saved --timeout 3` → 读取你自己的那条配置,`found=true`、`value=个性化`、退出码 0 +- [x] 回归:三来源控件树、拾取下钻、列表读取(三例均 5 行 × 3 列)、监控列表加载全部正常;Release 与 Debug 均已编译 + +#### 第八轮:区域标题 / 启用列 / 选中状态 + +- [x] 每个区域加**标题栏**(浅灰底、加粗 22px),不用再靠内容猜是什么:窗口列表 / 控件摘要 / 控件属性 / 控件监控列表;布局自检也纳入了这 4 个标题(实测各 22px、异常区域 0 个) +- [x] 监控列表新增**「启用」复选框**列:停用的条目保留在配置里但无界面模式会跳过它 + - 持久化字段命名为 `Disabled` 且缺省省略,**老配置文件没有该字段 = 全部启用**(不会因为新增字段把已保存的监控全部停用) + - 点击复选框立即提交(`CurrentCellDirtyStateChanged` + `CommitEdit`),否则要等焦点离开才写回对象 +- [x] `valueKey` 新增**「选中状态」**(跨来源键): + - UIA:`SelectionItemPattern.Current.IsSelected` → 是 / 否;该控件不支持该 Pattern 时明确报"无法判断是否被选中(列表行/列表项通常支持)" + - MSAA:读状态位 → 是 / 有焦点但未选中 / 否 + - Win32:窗口本身没有选中概念,会明确报不支持 + - 另有 UIA 专用键 `IsSelected`(true/false 原文) +- [x] 无界面 JSON 汇总新增 `Skipped`(停用跳过数),`Total` 改为"配置里的条目总数",于是 `命中 + 未定位 + 取不到值 + 跳过 = 总数` +- [x] 实测:停用条目被跳过(`Skipped=1`,报告里不含它);`选中状态` 对不支持的就是明确报错、对 MSAA 任务栏返回"否";`accRole` 返回"客户区" + +#### 第九轮:界面收敛 + 监控项增强 + 设置框架 + +- [x] 去掉「控件摘要」区域(`ControlPathBuilder` 随之删除);每个区域的标题只剩必要信息(第 11 条:窗口列表标题不再带描述) +- [x] 「内容Key」在界面上一律显示为**别名**(JSON 字段名仍是 `ContentKey`,老配置可读) +- [x] **RuntimeId 不再为空**:树快照仍是按需读取(省每节点一次跨进程调用),但选中节点/拾取目标时会读一次再刷新属性网格 +- [x] 监控列表列改为 `启用 | 控件Path | 别名 | 来源 | valueKey | 焦点 | 超时秒`:隐藏 value 列;**页面特征移到属性网格**可编辑(**留空 = 不校验页面特征**,校验规则同步放宽) +- [x] **点行头三角即定位**:新增 `定位到控件` 与 `刷新状态` 按钮,行头点击也触发;定位成功后在屏幕上画出与拾取器同一套**不抢焦点的高亮框**,并把该行「焦点」列填上 +- [x] 「刷新状态」逐条定位并读焦点,**每条独立计时**,一条等不到不影响其他 +- [x] 新增跨来源 valueKey **`焦点状态`**(UIA `HasKeyboardFocus` / MSAA `STATE_SYSTEM_FOCUSED` / Win32 比前台窗口),`HasKeyboardFocus` 纳入缓存不增加每节点调用 +- [x] 监控项新增 `TimeoutSeconds`(0 = 用全局 `--timeout`);无界面读取优先用条目自己的超时,每条独立计时 +- [x] 窗口列表:**前台窗口**(屏幕上最上方那个)浅黄底色 + 提示,最小化窗口灰字 +- [x] 控件树搜索:默认一行(搜索框 / 仅显示匹配 / ▲▼ / 匹配 N 项 / 更多…),「更多」展开 名称·路径·AutomationId·类名·类型·仅焦点元素;过滤时保留祖先链,匹配项高亮,▲▼ 循环跳转 +- [x] 「列表结果」不再看起来没用:标签页上方常驻说明栏,读不到时写明状态/来源/原因与三步建议(换来源 → 激活无障碍 → 该控件可能不暴露表格结构) +- [x] **窗口匹配分级降级**:进程名+类名+标题 → 进程名+类名 → 进程名+标题 → 仅进程名,并在 resolution 里写明命中级别与"建议重新添加"。原因:WinForms 窗口类名带版本哈希,**程序升级后类名会变**;标题关键词可能随内容(文件名/患者名)变化 +- [x] **独立设置文件 `settings.json`**:exe 同目录、随编译拷到 Debug/Release(`None` + `PreserveNewest`,**不嵌入 exe**,工程内 0 个 `EmbeddedResource`);文件缺失自动生成默认值,文件损坏记日志并回退默认值(实测:故意写坏 JSON 仍能正常启动,"异常区域 0 个") +- [x] **设置界面**:关于(版本 + 如实写明能力边界 + 两个配置路径)/ 界面 / 悬浮按钮 / 命令 / OCR;保存后才写盘 +- [x] **命令执行**(工具生命周期钩子):`启动执行` `结束执行` `on`(按间隔持续,可停)`once`(启动时一次);通过 `cmd.exe /c` 以当前用户身份运行,带超时、捕获 stdout/stderr、输出进控制台日志;界面可增删改、立即执行、启停 +- [x] **悬浮按钮条**:置顶、不抢焦点(`ShowWithoutActivation` + `WS_EX_NOACTIVATE`)、可拖动、位置存设置;按钮可配置(读取选中控件列表 / 定位到控件 / 读取全部监控项 / 检查选中窗口 / 拾取控件) +- [ ] **OCR 本轮未实现**:设置里只有字段与横幅说明("本轮未实现,仅保存配置"),不假装能识别。实现需要引入引擎与中文语言包,并明确截图可能含患者信息、默认不上传外部服务 +- [x] 回归:三来源控件树(UIA 56 / MSAA 167 / Win32 7,含 ListView 句柄)、拾取下钻、列表读取三例 5 行×3 列、布局自检 93 个控件"异常区域 0 个"、`--read-saved` 仍 found/取值(实测读到 `系统`,随设置页面变化) + +#### 本轮暴露的限制(已实测,非推测) + +- [ ] **WinForms `DataGridView` 的单元格值无法通过 UIA 读取**:`TablePattern` 能给出正确的行列数,但 `GetItem` 每次都抛 `E_UNEXPECTED`/`ElementNotAvailable`,随后该 HWND 的整个 UIA Provider 失效(连 `FromHandle` 都失败)。当前实现会如实报告 Partial + 明确提示,不会伪造数据。若要读取,需要评估 Win32 消息 / 跨进程读取方案(见下方待办) +- [ ] 遍历降级读到的行数只是“当前已实现的行”,虚拟化或滚动出视图的行读不到;UI 已显示为“未知(已读 N 行)”,仍需要在真实 PACS 上确认可接受 +- [ ] 旧式 `SysListView32` 通过 MSAA 桥只暴露第一列文本时,子列可能只有 `Name`,需要在真实 PACS 列表上复核 +- [ ] 列表读取期间仍可能被卡死的 Provider 占住后台线程;已改为独立线程(`LongRunning`,不占线程池)并限制并发读取数,但无法强制中断 +- [ ] 用 `CacheRequest` 降低跨进程调用次数(当前每个元素仍是多次 `.Current.*` 查询),读大表时建议做 +- [ ] 控件监控列表目前只做“定义与保存”,尚未接入页面识别与自动读取(属于第四/五阶段) + +## 第三阶段:独立操作面板与右键能力评估 + +- [ ] 调查目标 PACS 是否提供官方插件、扩展或菜单注册机制 +- [ ] 无合法扩展机制时禁止外部进程菜单注入,采用独立操作条 +- [ ] 实现读取选中行、当前单元格、刷新、复制和导出操作 +- [ ] 区分观察右键、获取右键位置、拦截右键和修改菜单 + +## 第四阶段:页面规则与自动读取 + +- [ ] 设计带唯一 ID 和版本号的 JSON 页面规则 +- [ ] 组合进程、顶层窗口、标题关键词、类名、UIA 特征和关键控件识别 +- [ ] 实现页面进入、退出、变化判断和事件防抖 +- [ ] 控件失效后重新绑定,防止重复触发和读取循环 +- [ ] 增加手动测试规则功能 + +## 第五阶段:监控引擎 + +- [ ] 实现多窗口、多页面规则和独立任务 ID +- [ ] 将 UIA 事件回调限制为投递后台任务,不在回调中执行耗时读取/截图 +- [ ] 实现任务队列、超时取消、重试、暂停、恢复、启动、停止和状态查询 +- [ ] 实现资源释放、异常恢复、日志滚动和敏感信息脱敏 + +## 第六阶段:截图 + +- [ ] 实现窗口完整区域、客户区和子窗口截图 +- [ ] 对比 `PrintWindow`、`BitBlt`、`Graphics.CopyFromScreen` +- [ ] 独立测试最小化、遮挡、GPU、DirectX、OpenGL 和 PACS 影像区域 +- [ ] 评估 Windows Graphics Capture 的高版本可选实现 +- [ ] 未验证成功时返回“无法保证”,禁止将空白截图标记为成功 + +## 安全、部署与发布 + +- [ ] 默认只读,不注入目标进程、不修改内存、不绕过登录或授权 +- [ ] 配置截图保存目录、保留期限、清理规则和脱敏模式 +- [ ] 检查 .NET Framework 4.8 前置条件并制作安装包 +- [ ] 代码签名、部署、卸载和 Windows 7/10/11 发布矩阵验证 diff --git a/docs/描述.md b/docs/描述.md new file mode 100644 index 0000000..1f0c2af --- /dev/null +++ b/docs/描述.md @@ -0,0 +1,728 @@ +# AI 开发提示词:PACS 医疗客户端监控与控件自动化工具 + +## 一、你的角色 + +你是一名资深 Windows 桌面开发工程师、Windows UI Automation 专家、医疗软件集成工程师和测试驱动开发工程师。 + +请为我设计并开发一套完整的 **PACS 医疗客户端监控、窗口识别、控件拾取、列表读取、页面识别和截图工具**。 + +我需要的是可以逐步编译、运行、测试和交付的真实项目,而不是概念方案、伪代码或仅供参考的示例。 + +开发过程中必须充分考虑 Windows 7、Windows 10、Windows 11 的兼容性,以及医疗客户端常见的传统控件、第三方控件、嵌入式浏览器、自绘控件和权限限制。 + +所有功能必须围绕实际可验证的 Windows API 和系统能力实现。对于技术上无法保证的功能,必须明确说明限制,并提供可行的替代方案,不允许虚构 API 或承诺不可能实现的能力。 + +--- + +## 二、项目核心目标 + +开发一个独立运行的 Windows 桌面工具,用于监控指定 PACS 客户端的窗口和控件。 + +工具应当允许用户: + +1. 使用十字拾取器快速选择屏幕上的任意窗口或控件。 +2. 查看被选中控件的完整属性、父子层级及可访问性信息。 +3. 监控指定列表控件,读取列表行、列、单元格和选中项。 +4. 尝试在目标列表的右键菜单中增加自定义读取入口;不支持时,通过本工具的悬浮操作按钮或独立控制面板执行读取。 +5. 针对特定页面建立读取规则,并在页面出现时自动执行。 +6. 对指定窗口进行截图,包括窗口正常显示、被遮挡和最小化时的截图能力评估与实现。 +7. 导出控件信息、读取结果、截图和诊断日志。 +8. 通过统一配置适配不同 PACS 软件和不同 Windows 版本。 + +本项目主要用于经过授权的医疗客户端监控和系统集成。默认只读,不得擅自修改患者信息、检查数据或医疗业务记录。 + +--- + +## 三、技术选型与兼容性原则 + +### 3.1 核心技术 + +首选以下技术: + +* 开发语言:C#。 +* 主运行环境:.NET Framework 4.8,明确验证 Windows 7 SP1、Windows 10、Windows 11 的实际部署条件。 +* 窗口识别:Windows 原生 Win32 API。 +* 控件识别:微软原生 UI Automation。 +* 控件操作:UI Automation Control Patterns。 +* 传统控件补充:Win32 API、Windows 消息、必要时 MSAA/IAccessible。 +* 图像处理:根据需要引入兼容的 OpenCV 版本。 +* OCR:作为可选扩展模块,支持中文界面文字识别。 +* 配置文件:JSON。 +* 日志:结构化文本日志,支持日志滚动和异常记录。 +* 自动化测试:使用与目标框架兼容的测试框架和独立测试项目。 + +不使用 FlaUI,不引入 FlaUI.UIA2 或 FlaUI.UIA3。 + +### 3.2 原生 UI Automation + +通过系统程序集引用: + +* UIAutomationClient +* UIAutomationTypes + +核心命名空间: + +* System.Windows.Automation + +重点使用: + +* AutomationElement +* AutomationElement.FromHandle +* TreeWalker +* TreeScope +* PropertyCondition +* AutomationElement.FindAll +* ValuePattern +* TextPattern +* InvokePattern +* SelectionPattern +* SelectionItemPattern +* ExpandCollapsePattern +* ScrollPattern +* Automation.AddAutomationEventHandler +* Automation.AddStructureChangedEventHandler + +必须在实际开发时核实具体 API、事件、控件模式以及对应系统版本的支持情况。 + +### 3.3 Win32 API + +按需使用: + +* EnumWindows +* EnumChildWindows +* FindWindow +* FindWindowEx +* GetWindowText +* GetClassName +* GetWindowThreadProcessId +* IsWindowVisible +* IsIconic +* GetWindowRect +* GetClientRect +* GetWindowPlacement +* GetForegroundWindow +* GetAncestor +* GetWindowLongPtr,按目标架构和系统版本进行兼容封装 +* SetWinEventHook +* GetGUIThreadInfo +* PrintWindow +* SendMessageTimeout +* RegisterWindowMessage +* GetDpiForWindow 等版本相关 API 的能力检测与降级封装 + +对于 Windows 7 不存在的 API,必须使用版本检测、动态加载或兼容实现,禁止直接调用后导致程序在旧系统上启动失败。 + +### 3.4 架构原则 + +1. 不允许依赖 FlaUI。 +2. UI Automation 与 Win32 API 必须分层封装。 +3. 业务逻辑不得直接散落大量 P/Invoke。 +4. 不得把 HWND、UIA 元素和图像识别结果混为同一种对象。 +5. 每个读取结果必须保留来源、时间、识别方式和可信状态。 +6. 所有操作都必须支持超时、异常捕获和取消。 +7. 不能保证读取成功时,应明确返回不支持或无法确认,不得伪造数据。 +8. 所有关键模块都必须提供可独立运行的测试。 + +--- + +## 四、功能一:十字拾取器 + +开发一个类似 Spy++、Inspect 工具的十字拾取器,用于快速识别 PACS 窗口和控件。 + +### 4.1 操作方式 + +主界面提供“拾取控件”按钮。 + +用户按下按钮后: + +1. 鼠标指针切换为十字准星。 +2. 实时显示当前指针下方的窗口和控件信息。 +3. 可以按住鼠标左键拖动十字准星。 +4. 松开鼠标后,确定当前目标。 +5. 支持按 Esc 取消。 +6. 支持拾取顶层窗口、子窗口和 UIA 元素。 +7. 支持拾取成功后自动高亮目标区域。 + +不得让拾取器自身的窗口被错误识别为目标。 + +### 4.2 实时信息 + +拾取过程中尽可能显示: + +* HWND。 +* PID。 +* 进程名。 +* 窗口标题。 +* 窗口类名。 +* 父窗口 HWND。 +* 顶层窗口 HWND。 +* 窗口矩形。 +* 客户区矩形。 +* 窗口是否可见。 +* 窗口是否最小化。 +* UIA Name。 +* AutomationId。 +* ControlType。 +* ClassName。 +* FrameworkId。 +* NativeWindowHandle。 +* IsEnabled。 +* IsOffscreen。 +* BoundingRectangle。 +* 支持的 Pattern。 +* UIA Provider 是否可正常访问。 +* 目标识别失败原因。 + +对于不能获得的属性,返回 null 或明确的错误状态。 + +### 4.3 拾取算法 + +请实现以下策略: + +1. 通过鼠标位置定位底层 HWND。 +2. 获取窗口层级和进程信息。 +3. 尝试从 UIA 的鼠标位置定位能力中获取 UIA 元素。 +4. 如果 UIA 不可用,则退回 Win32 窗口信息。 +5. 如果目标是无真实子窗口的自绘控件,应提示用户此目标可能需要图像识别。 +6. 不得把屏幕坐标对应的 HWND 直接认定为真实业务控件。 + +请分析并选择合适的 API,包括 WindowFromPoint、GetAncestor、AutomationElement.FromPoint 等。 + +### 4.4 高亮显示 + +高亮框必须: + +* 不遮挡目标控件。 +* 不获取鼠标输入。 +* 不抢夺目标窗口焦点。 +* 不影响目标应用操作。 +* 支持 DPI 缩放和多显示器。 +* 支持取消和自动消失。 + +高亮框优先采用透明、无激活的独立窗口。 + +--- + +## 五、功能二:列表控件监控和右键操作 + +这是项目重点功能。 + +需要能够对 PACS 工作列表、检查列表、患者列表、报告列表等控件进行识别、读取和监控。 + +### 5.1 列表识别 + +支持尽可能识别以下控件: + +* ListView。 +* DataGrid。 +* Table。 +* Tree。 +* ComboBox。 +* ListBox。 +* 第三方表格。 +* 自绘列表。 +* 嵌入式网页表格。 + +需要识别: + +* 列名。 +* 行数。 +* 列数。 +* 当前选中行。 +* 当前选中单元格。 +* 单元格文本。 +* 行标识。 +* 列标识。 +* 当前排序状态(如果可获得)。 +* 滚动状态。 +* 可见行与总行数。 +* 控件坐标。 +* 当前数据读取方式。 +* 数据是否完整。 +* 读取失败原因。 + +优先使用 UIA 的 GridPattern、TablePattern、SelectionPattern、SelectionItemPattern、TextPattern 等适用模式。 + +对于不支持上述 Pattern 的列表,依次尝试: + +1. UIA 子元素遍历。 +2. Win32 原生控件消息。 +3. MSAA/IAccessible。 +4. 经授权的应用官方接口。 +5. OCR 和图像分析。 + +不得假设所有表格都有 GridPattern。 + +不得把屏幕上可见的文字直接当作完整的数据源。 + +### 5.2 右键菜单集成 + +实现两种方案,并评估可行性。 + +方案 A:在目标 PACS 列表的右键菜单中添加“读取选中数据”。 + +方案 B:在本工具中提供独立的右键操作或悬浮按钮。 + +对于方案 A,必须先判断菜单属于哪种类型: + +* 原生 Win32 菜单。 +* UIA 暴露的菜单。 +* 目标程序自绘菜单。 +* 第三方框架菜单。 +* Web 页面上下文菜单。 + +只有在目标软件明确支持插件、扩展、菜单注册或其他合法扩展机制时,才优先采用原生菜单集成。 + +不得默认认为可以从外部进程安全地向任意 PACS 软件的内部右键菜单插入菜单项。 + +如果无法安全实现,应采用方案 B。 + +### 5.3 方案 B:独立读取按钮 + +主界面或浮动工具栏提供: + +* 读取选中行。 +* 读取当前单元格。 +* 读取整个列表。 +* 读取当前页面。 +* 导出 JSON。 +* 导出 CSV。 +* 复制读取结果。 +* 刷新控件信息。 + +用户在 PACS 列表上选中一行后,点击本工具按钮即可读取。 + +执行读取前必须确认: + +* 目标窗口 PID 与配置一致。 +* 目标控件身份仍然有效。 +* 当前选中项确实存在。 +* 控件未被销毁或替换。 +* 读取操作不会改变患者数据或检查数据。 + +### 5.4 右键事件监控 + +支持通过合适的 Windows 事件机制和应用内交互观察目标控件的操作状态。 + +必须区分: + +* 观察右键发生。 +* 获取右键位置。 +* 获取当前选中项。 +* 拦截右键事件。 +* 修改目标程序的右键菜单。 + +这些是不同的能力,不得混为一谈。 + +默认不全局拦截鼠标,不注入目标进程,不修改 PACS 内部代码。 + +--- + +## 六、功能三:特定页面读取 + +需要设计可配置的页面识别规则,针对指定 PACS 页面自动读取信息。 + +### 6.1 页面规则 + +每个页面可以配置: + +* 页面名称。 +* 目标进程名。 +* 主窗口标题关键词。 +* 主窗口类名。 +* HWND 识别规则。 +* 父窗口和子窗口关系。 +* 页面关键控件。 +* 必须存在的 UIA 元素。 +* 页面识别条件。 +* 读取任务列表。 +* 读取间隔。 +* 超时时间。 +* 触发事件。 +* 页面退出条件。 + +禁止仅依赖窗口标题判断页面身份,因为多个页面可能共享同一个标题。 + +### 6.2 页面识别方式 + +采用组合式识别: + +1. 进程和顶层窗口。 +2. 窗口标题和类名。 +3. UIA 控件树特征。 +4. 特征控件的 Name、AutomationId、ControlType。 +5. 页面内独特的文本或按钮。 +6. 必要时通过 OCR 辅助判断。 + +每个页面规则应有唯一 ID 和版本号。 + +### 6.3 触发方式 + +支持: + +* 手动读取。 +* 用户切换到目标页面时读取。 +* 窗口结构变化时读取。 +* 指定控件出现时读取。 +* 轮询检查页面状态。 +* 页面识别成功后执行一次读取。 +* 仅在页面数据发生变化时读取。 + +事件驱动优先,轮询作为补充。 + +需要防止事件重复触发、读取循环、线程阻塞、窗口销毁和控件失效。 + +### 6.4 输出格式 + +统一返回: + +* 页面规则 ID。 +* 目标窗口信息。 +* 页面识别结果。 +* 控件路径。 +* 字段名。 +* 字段值。 +* 读取方式。 +* 读取时间。 +* 数据可信状态。 +* 错误代码。 +* 错误说明。 + +不得默认把患者姓名、身份证号、检查结果等敏感数据写入普通调试日志。 + +--- + +## 七、功能四:指定窗口截图 + +需要支持对指定窗口截图,而不只是对整个屏幕截图。 + +### 7.1 基础功能 + +支持: + +1. 指定 HWND 截图。 +2. 指定进程的主窗口截图。 +3. 指定窗口客户区截图。 +4. 指定窗口完整区域截图。 +5. 指定子窗口截图。 +6. 定时截图。 +7. 页面识别成功后自动截图。 +8. 读取失败时自动保存诊断截图。 +9. 保存 PNG、JPEG。 +10. 截图与控件信息、日志关联。 + +截图记录应包含: + +* HWND。 +* PID。 +* 进程名。 +* 窗口标题。 +* 窗口状态。 +* 截图时间。 +* 截图方式。 +* 截图是否完整。 +* 失败原因。 +* 文件路径。 + +### 7.2 窗口显示时截图 + +请分别实现并比较: + +* PrintWindow。 +* BitBlt。 +* Graphics.CopyFromScreen。 +* Windows Graphics Capture(作为可选的高版本方案)。 + +根据目标窗口、系统版本和实际测试选择适用方式。 + +需要说明: + +* CopyFromScreen 截取的是屏幕可见内容,窗口被遮挡时会受影响。 +* PrintWindow 的效果取决于目标应用的绘制实现,不能保证对所有窗口有效。 +* 某些 DirectX、OpenGL、GPU 加速或特殊渲染界面可能产生黑屏、空白或不完整图像。 + +### 7.3 最小化窗口截图 + +必须把最小化截图作为独立测试项目。 + +不能简单声称 PrintWindow 可以对所有最小化窗口截图。 + +请设计如下流程: + +1. 检查目标窗口是否最小化。 +2. 尝试在不改变目标窗口状态的前提下执行可用截图方式。 +3. 验证截图是否有效,不能只判断 API 是否返回成功。 +4. 如果失败,记录失败原因。 +5. 尝试适用的替代方法。 +6. 只有在用户明确授权时,才允许临时恢复窗口。 +7. 如需恢复窗口,优先使用独立窗口状态快照,并尽可能恢复原来的最小化状态、前台窗口和焦点。 +8. 提示用户:恢复窗口可能造成屏幕闪动、改变前台状态,不能保证完全无感。 +9. 对 GPU 加速、自绘控件和视频区域,提供能力限制说明。 + +请特别分析以下几种情形: + +* 普通 Win32 窗口最小化。 +* WPF / WinForms 窗口最小化。 +* DirectX / OpenGL 渲染窗口最小化。 +* PACS 影像浏览器最小化。 +* 窗口被其他窗口遮挡但未最小化。 +* 窗口位于其他桌面或远程会话。 + +如果系统或目标应用不支持真正的最小化后台截图,必须明确返回“无法保证”,不能生成空白截图并当作成功。 + +--- + +## 八、监控引擎 + +设计一个独立监控服务,支持: + +* 多窗口监控。 +* 多个页面规则。 +* 多个列表控件。 +* 控件失效检测。 +* 页面进入和退出事件。 +* 定时任务。 +* 超时取消。 +* 读取任务队列。 +* 错误重试。 +* 运行状态查询。 +* 暂停和恢复。 +* 启动和停止。 +* 异常自动恢复。 +* 防止重复任务。 +* 资源释放。 +* 日志滚动。 + +每个监控任务必须具备独立的任务 ID。 + +不允许在 UIA 事件回调中执行耗时读取或截图操作;应把任务交给后台工作队列。 + +需要正确处理 UIA 元素在页面变化后失效的情况,必要时重新获取元素。 + +--- + +## 九、数据安全和权限要求 + +由于目标是 PACS 医疗客户端,必须遵守以下要求: + +1. 默认只读。 +2. 不自动修改患者信息。 +3. 不自动删除或提交医疗记录。 +4. 不绕过登录、访问控制或权限验证。 +5. 不擅自注入目标进程。 +6. 不修改目标程序内存。 +7. 不绕过软件授权。 +8. 日志默认不保存完整患者敏感信息。 +9. 截图应提供保存目录、保留期限和清理规则。 +10. 支持脱敏模式。 +11. 对导出数据记录操作来源和时间。 +12. 对可能改变业务状态的操作提供二次确认。 +13. 不应将真实患者数据上传到外部 OCR 或 AI 服务,除非经过明确授权和安全审查。 + +--- + +## 十、界面设计 + +主界面至少包括: + +### 10.1 窗口列表 + +显示: + +* 窗口标题。 +* 进程名。 +* PID。 +* HWND。 +* 类名。 +* 可见状态。 +* 最小化状态。 + +支持刷新、搜索和手动绑定窗口。 + +### 10.2 控件检查器 + +显示: + +* 控件树。 +* 控件属性。 +* 父子关系。 +* 坐标。 +* 可访问性状态。 +* 支持的 Pattern。 +* 读取结果。 +* 错误信息。 + +支持十字拾取器定位并高亮控件。 + +### 10.3 列表读取器 + +支持: + +* 当前选中行读取。 +* 当前单元格读取。 +* 全部可访问行读取。 +* 列名读取。 +* JSON / CSV 导出。 +* 手动刷新。 + +### 10.4 页面规则管理 + +支持新增、编辑、删除、启用、禁用、测试页面规则。 + +### 10.5 截图管理 + +支持选择窗口、截图方式、定时截图、最小化截图测试、查看截图状态和打开保存目录。 + +### 10.6 监控日志 + +支持按任务、时间、窗口、错误类型筛选日志。 + +--- + +## 十一、兼容性策略 + +### Windows 7 + +* 必须针对 Windows 7 SP1 实机验证。 +* 检查 .NET Framework 4.8 的安装条件。 +* 禁止未经检测就直接调用新系统 API。 +* 对高版本 API 使用动态加载和功能降级。 +* 测试 UIA、Win32、MSAA 的实际能力。 +* 不得假设所有新式 UIA 功能均存在。 + +### Windows 10 + +* 测试不同 DPI 缩放。 +* 测试多显示器。 +* 测试管理员权限和普通权限。 +* 测试不同 PACS 客户端架构。 +* 测试窗口遮挡和最小化截图。 + +### Windows 11 + +* 测试现代桌面窗口。 +* 测试高 DPI。 +* 测试高权限窗口。 +* 测试 UIA 事件和控件失效。 +* 测试多显示器与远程桌面场景。 + +### 统一原则 + +同一份业务代码优先覆盖三个系统。 + +对不同系统的差异使用能力检测和适配层,而不是把整个项目复制成三个版本。 + +--- + +## 十二、测试驱动开发要求 + +必须采用分阶段 TDD。 + +每个模块按以下顺序开发: + +1. 编写需求和验收标准。 +2. 编写测试。 +3. 编写最小实现。 +4. 编译。 +5. 运行测试。 +6. 处理失败。 +7. 补充边界测试。 +8. 更新文档。 +9. 再开发下一模块。 + +必须提供: + +* 单元测试。 +* Windows 集成测试。 +* 目标客户端手工验收清单。 +* Win7、Win10、Win11 兼容性矩阵。 +* 异常恢复测试。 +* 性能测试。 +* 资源释放测试。 + +无法在当前开发环境验证的内容必须标记为“待目标系统实测”,不能伪造测试结果。 + +--- + +## 十三、验收标准 + +### 窗口识别 + +* 能枚举符合权限范围的顶层窗口。 +* 能获取 HWND、PID、标题、类名。 +* 能筛选指定 PACS 进程。 +* 能定位目标窗口。 +* 能正确处理窗口销毁。 + +### 十字拾取器 + +* 能拾取窗口。 +* 能尝试拾取 UIA 元素。 +* 能显示基本属性。 +* 能取消拾取。 +* 能高亮目标。 +* 不得将工具自身窗口错误识别为目标。 + +### 列表读取 + +* 能识别目标列表。 +* 能读取实际可访问的行列数据。 +* 能读取当前选中项。 +* 能报告无法读取的控件。 +* 不得把不完整结果伪装成完整结果。 + +### 页面识别 + +* 能根据配置识别指定页面。 +* 能避免重复触发。 +* 能在页面切换后重新绑定控件。 +* 能记录读取结果和错误。 + +### 截图 + +* 能指定 HWND 截图。 +* 能截图客户区。 +* 能验证截图是否有效。 +* 能测试最小化窗口截图。 +* 不能实现的截图场景必须返回明确状态。 + +### 兼容性 + +* Windows 7 SP1。 +* Windows 10。 +* Windows 11。 + +三个系统均需完成实际运行测试,不能仅凭编译成功就宣布兼容。 + +--- + +## 十四、AI 必须交付的内容 + +请按以下顺序输出: + +1. 完整技术方案。 +2. 系统架构图。 +3. 项目目录结构。 +4. 依赖清单及版本选择理由。 +5. Windows API 兼容性清单。 +6. 数据模型和接口定义。 +7. 第一阶段完整可编译代码。 +8. 单元测试和集成测试。 +9. 第二阶段完整代码。 +10. 后续阶段开发计划。 +11. 部署说明。 +12. Windows 7、Windows 10、Windows 11 测试清单。 +13. 已知限制和替代方案。 +14. 打包与发布方案。 + +每次只实现一个可编译、可验证的阶段。不要一次生成大量互相依赖、无法编译的代码。 + +如果输出内容过长,应按文件拆分,明确文件路径、完整代码和执行步骤。 + +不得用伪代码代替核心实现。不得省略关键依赖。不得假设目标 PACS 软件提供不存在的接口。 + +首先请完成: + +**第一阶段:项目基础架构 + 窗口枚举 + 十字拾取器 + UIA 控件属性检查 + 控件树导出。** + +要求给出完整项目代码、依赖配置、编译步骤、运行方式、测试用例和兼容性风险。完成后再继续列表读取、页面监控和截图功能。 diff --git a/pacs_win_uia.sln b/pacs_win_uia.sln new file mode 100644 index 0000000..3788963 --- /dev/null +++ b/pacs_win_uia.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "pacs_win_uia", "src\pacs_win_uia\pacs_win_uia.csproj", "{C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/pacs_win_uia/Diagnostics/AppLog.cs b/src/pacs_win_uia/Diagnostics/AppLog.cs new file mode 100644 index 0000000..0810d66 --- /dev/null +++ b/src/pacs_win_uia/Diagnostics/AppLog.cs @@ -0,0 +1,249 @@ +using System; +using System.IO; +using System.Text; +using pacs_win_uia.Interop; + +namespace pacs_win_uia.Diagnostics +{ + public enum LogLevel + { + Debug, + Info, + Warn, + Error + } + + /// + /// 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(); + private static NativeMethods.ConsoleCtrlHandler _consoleCtrlHandler; + private static bool _consoleReady; + private static bool _initialized; + 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) + { + if (_initialized) + { + return; + } + + _initialized = true; + try + { + _consoleReady = PrepareConsole(); + if (_consoleReady) + { + // Closing the console window must not terminate the tool: the tool + // window stays usable and the log can be reopened by restarting. + _consoleCtrlHandler = HandleConsoleControl; + NativeMethods.SetConsoleCtrlHandler(_consoleCtrlHandler, true); + } + } + catch + { + _consoleReady = false; + } + + WriteRaw(LogLevel.Info, "日志已启动:" + DescribeConsole()); + } + } + + 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); + } + + private static void Write(LogLevel level, string message, Exception exception) + { + if (level < _minimumLevel) + { + return; + } + + var builder = new StringBuilder(); + if (!string.IsNullOrEmpty(message)) + { + builder.Append(message); + } + + if (exception != null) + { + if (builder.Length > 0) + { + builder.Append(" | "); + } + + builder.Append(DescribeException(exception)); + } + + WriteRaw(level, builder.ToString()); + } + + private static void WriteRaw(LogLevel level, string message) + { + if (!_consoleReady) + { + return; + } + + try + { + string line = DateTime.Now.ToString("HH:mm:ss.fff") + " [" + level.ToString().ToUpperInvariant() + "] " + message; + lock (Sync) + { + Console.Out.WriteLine(line); + Console.Out.Flush(); + } + } + catch + { + // Console output is best effort; a broken console must not break the tool. + } + } + + private static string DescribeException(Exception exception) + { + var builder = new StringBuilder(); + Exception current = exception; + int depth = 0; + while (current != null && depth < 4) + { + if (depth > 0) + { + builder.Append(" <- "); + } + + builder.Append(current.GetType().Name).Append(": ").Append(current.Message); + current = current.InnerException; + depth++; + } + + return builder.ToString(); + } + + private static string DescribeConsole() + { + return _consoleReady ? "已输出到控制台窗口。" : "当前进程没有可用的控制台,日志已禁用。"; + } + + private static bool PrepareConsole() + { + if (NativeMethods.GetConsoleWindow() != IntPtr.Zero) + { + RedirectStandardStreams(); + return true; + } + + // Terminals and IDEs that use pipes (mintty/Git Bash, captured IDE output, a redirected + // file) have no console window, and there AllocConsole fails with ACCESS_DENIED because a + // pseudo-console is already attached. The existing standard output is the log sink, and + // re-opening it would break it. + if (HasUsableStandardOutput()) + { + return true; + } + + // Running from a terminal that hands us a real parent console. + if (NativeMethods.AttachConsole(NativeMethods.ATTACH_PARENT_PROCESS)) + { + RedirectStandardStreams(); + return true; + } + + // Plain double-click launch: own a console window so the log is visible. + if (NativeMethods.AllocConsole()) + { + RedirectStandardStreams(); + return true; + } + + return false; + } + + private static bool HasUsableStandardOutput() + { + try + { + IntPtr handle = NativeMethods.GetStdHandle(NativeMethods.STD_OUTPUT_HANDLE); + if (handle == IntPtr.Zero || handle == new IntPtr(-1)) + { + return false; + } + + return NativeMethods.GetFileType(handle) != NativeMethods.FILE_TYPE_UNKNOWN; + } + catch + { + return false; + } + } + + private static void RedirectStandardStreams() + { + // Console caches its writers on first use; re-open them so output reaches the + // console attached above instead of a stale or missing handle. The console's own + // encoding is kept: forcing UTF-8 would garble Chinese text in a GBK console window. + try + { + var standardOutput = new StreamWriter(Console.OpenStandardOutput()) + { + AutoFlush = true + }; + Console.SetOut(standardOutput); + } + catch + { + // Keep the default writer when the standard handle cannot be re-opened. + } + } + + private static bool HandleConsoleControl(uint controlType) + { + // Swallow the close/logoff events so closing the log window cannot kill the tool. + return controlType == NativeMethods.CTRL_CLOSE_EVENT; + } + } +} diff --git a/src/pacs_win_uia/Interop/MsaaNativeMethods.cs b/src/pacs_win_uia/Interop/MsaaNativeMethods.cs new file mode 100644 index 0000000..5fd4f73 --- /dev/null +++ b/src/pacs_win_uia/Interop/MsaaNativeMethods.cs @@ -0,0 +1,244 @@ +using System; +using System.Runtime.InteropServices; +using Accessibility; + +namespace pacs_win_uia.Interop +{ + /// + /// 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 + /// mistake there is an access violation rather than a managed exception. + /// + /// All four functions return an HRESULT, so PreserveSig keeps failures as return codes instead + /// of exceptions; every call site checks the code. + /// + internal static class MsaaNativeMethods + { + internal const uint OBJID_WINDOW = 0x00000000; + internal const uint OBJID_CLIENT = 0xFFFFFFFC; + internal const int CHILDID_SELF = 0; + internal const int S_OK = 0; + + internal static readonly Guid IID_IAccessible = new Guid("618736E0-3C3D-11CF-810C-00AA00389B71"); + + [DllImport("oleacc.dll", PreserveSig = true)] + internal static extern int AccessibleObjectFromWindow( + IntPtr hwnd, + uint dwObjectId, + 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); + + /// + /// Batched child read. The object[] + ArraySubType=Struct + SizeParamIndex=2 form lets the + /// marshaller own the VARIANTs; manual IntPtr/VariantClear leaks COM references and crashes. + /// + [DllImport("oleacc.dll", PreserveSig = true)] + internal static extern int AccessibleChildren( + IAccessible pacc, + int iChildStart, + int cChildren, + [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Struct, SizeParamIndex = 2)] + object[] rgvarChildren, + out int pcObtained); + + /// + /// Window behind an accessible object. Succeeds with hwnd == NULL for windowless objects, + /// so callers must check both the HRESULT and the handle. + /// + [DllImport("oleacc.dll", PreserveSig = true)] + internal static extern int WindowFromAccessibleObject(IAccessible pacc, out IntPtr phwnd); + } + + /// ROLE_SYSTEM_* and STATE_SYSTEM_* names, from oleacc.h. + internal static class MsaaConstants + { + private static readonly string[] RoleNames = BuildRoleNames(); + private static readonly string[] StateNames = BuildStateNames(); + + internal static string DescribeRole(object role) + { + if (role == null) + { + return "(无角色)"; + } + + if (role is string) + { + return (string)role; + } + + int id = ToInt(role, -1); + if (id < 0) + { + return "(无角色)"; + } + + return id < RoleNames.Length && RoleNames[id] != null + ? RoleNames[id] + : "角色" + id; + } + + internal static string DescribeState(object state) + { + if (state == null) + { + return string.Empty; + } + + if (state is string) + { + return (string)state; + } + + int value = ToInt(state, 0); + var parts = new System.Collections.Generic.List(); + for (int index = 0; index < StateNames.Length; index++) + { + if (StateNames[index] == null) + { + continue; + } + + int mask = 1 << index; + if ((value & mask) != 0) + { + parts.Add(StateNames[index]); + } + } + + return string.Join(",", parts.ToArray()); + } + + internal static int ToInt(object value, int fallback) + { + if (value is int) + { + return (int)value; + } + + if (value is short) + { + return (short)value; + } + + if (value is uint) + { + return unchecked((int)(uint)value); + } + + return fallback; + } + + private static string[] BuildRoleNames() + { + var names = new string[0x41]; + names[0x01] = "标题栏"; + names[0x02] = "菜单栏"; + names[0x03] = "滚动条"; + names[0x04] = "尺寸柄"; + names[0x05] = "声音"; + names[0x06] = "光标"; + names[0x07] = "插入符"; + names[0x08] = "警告"; + names[0x09] = "窗口"; + names[0x0A] = "客户区"; + names[0x0B] = "弹出菜单"; + names[0x0C] = "菜单项"; + names[0x0D] = "工具提示"; + names[0x0E] = "应用程序"; + names[0x0F] = "文档"; + names[0x10] = "窗格"; + names[0x11] = "图表"; + names[0x12] = "对话框"; + names[0x13] = "边框"; + names[0x14] = "分组"; + names[0x15] = "分隔符"; + names[0x16] = "工具栏"; + names[0x17] = "状态栏"; + names[0x18] = "表格"; + names[0x19] = "列标题"; + names[0x1A] = "行标题"; + names[0x1B] = "列"; + names[0x1C] = "行"; + names[0x1D] = "单元格"; + names[0x1E] = "链接"; + names[0x1F] = "帮助气球"; + names[0x20] = "字符"; + names[0x21] = "列表"; + names[0x22] = "列表项"; + names[0x23] = "大纲"; + names[0x24] = "大纲项"; + names[0x25] = "页标签"; + names[0x26] = "属性页"; + names[0x27] = "指示器"; + names[0x28] = "图形"; + names[0x29] = "静态文本"; + names[0x2A] = "文本"; + names[0x2B] = "按钮"; + names[0x2C] = "复选框"; + names[0x2D] = "单选框"; + names[0x2E] = "组合框"; + names[0x2F] = "下拉列表"; + names[0x30] = "进度条"; + names[0x31] = "刻度盘"; + names[0x32] = "热键框"; + names[0x33] = "滑块"; + names[0x34] = "微调按钮"; + names[0x35] = "图"; + names[0x36] = "动画"; + names[0x37] = "公式"; + names[0x38] = "下拉按钮"; + names[0x39] = "菜单按钮"; + names[0x3A] = "网格下拉按钮"; + names[0x3B] = "空白"; + names[0x3C] = "页标签列表"; + names[0x3D] = "时钟"; + names[0x3E] = "拆分按钮"; + names[0x3F] = "IP 地址"; + names[0x40] = "大纲按钮"; + return names; + } + + private static string[] BuildStateNames() + { + var names = new string[31]; + names[0] = "不可用"; + names[1] = "已选中"; + names[2] = "有焦点"; + names[3] = "按下"; + names[4] = "已勾选"; + names[5] = "混合"; + names[6] = "只读"; + names[7] = "热跟踪"; + names[8] = "默认"; + names[9] = "已展开"; + names[10] = "已折叠"; + names[11] = "忙"; + names[12] = "浮动"; + names[13] = "跑马灯"; + names[14] = "动画"; + names[15] = "不可见"; + names[16] = "屏幕外"; + names[17] = "可调整大小"; + names[18] = "可移动"; + names[19] = "自述"; + names[20] = "可聚焦"; + names[21] = "可选中"; + names[22] = "已链接"; + names[23] = "已访问"; + names[24] = "可多选"; + names[25] = "可扩展选择"; + names[26] = "低级警告"; + names[27] = "中级警告"; + names[28] = "高级警告"; + names[29] = "受保护"; + return names; + } + } +} diff --git a/src/pacs_win_uia/Interop/NativeMethods.cs b/src/pacs_win_uia/Interop/NativeMethods.cs new file mode 100644 index 0000000..4b95bae --- /dev/null +++ b/src/pacs_win_uia/Interop/NativeMethods.cs @@ -0,0 +1,264 @@ +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Text; + +namespace pacs_win_uia.Interop +{ + internal static class NativeMethods + { + 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; + internal const int SW_HIDE = 0; + 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; + internal const int VK_ESCAPE = 0x1B; + internal const int VK_LBUTTON = 0x01; + internal const uint GA_PARENT = 1; + internal const uint GA_ROOT = 2; + internal const uint GA_ROOTOWNER = 3; + internal const uint SMTO_ABORTIFHUNG = 0x0002; + internal const uint SMTO_BLOCK = 0x0001; + internal const int ATTACH_PARENT_PROCESS = -1; + internal const uint CTRL_CLOSE_EVENT = 2; + + internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); + + internal const int STD_OUTPUT_HANDLE = -11; + internal const uint FILE_TYPE_UNKNOWN = 0; + + 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(); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool AttachConsole(int processId); + + [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(); + + [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); + + [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("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); + + internal const int WM_GETTEXT = 0x000D; + internal const int DWMWA_CLOAKED = 14; + internal const uint CWP_ALL = 0x0000; + internal const uint CWP_SKIPINVISIBLE = 0x0001; + internal const uint CWP_SKIPDISABLED = 0x0002; + 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 SendMessageTimeout( + IntPtr hWnd, + int msg, + IntPtr wParam, + StringBuilder lParam, + uint flags, + uint timeout, + out IntPtr result); + + [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); + + [DllImport("dwmapi.dll")] + internal static extern int DwmGetWindowAttribute(IntPtr hwnd, int attribute, out int value, int size); + + /// + /// One-call replacement for GetWindowRect + GetClientRect + ClientToScreen + style reads. + /// Both rectangles are in screen coordinates. + /// + [StructLayout(LayoutKind.Sequential)] + internal struct WINDOWINFO + { + 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; + } + + [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr GetWindowLongPtr64( + IntPtr hWnd, + int nIndex); + + [DllImport("user32.dll", EntryPoint = "GetWindowLong", SetLastError = true)] + private static extern int GetWindowLong32( + IntPtr hWnd, + int nIndex); + + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr SetWindowLongPtr64( + IntPtr hWnd, + int nIndex, + IntPtr dwNewLong); + + [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( + IntPtr hWnd, + IntPtr hWndInsertAfter, + int x, + int y, + int cx, + 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); + + internal static int GetWindowStyle(IntPtr hWnd) + { + if (IntPtr.Size == 8) + { + return unchecked((int)GetWindowLongPtr64(hWnd, GWL_EXSTYLE).ToInt64()); + } + + return GetWindowLong32(hWnd, GWL_EXSTYLE); + } + + internal static IntPtr SetWindowStyle(IntPtr hWnd, int style) + { + if (IntPtr.Size == 8) + { + return SetWindowLongPtr64(hWnd, GWL_EXSTYLE, new IntPtr(style)); + } + + return new IntPtr(SetWindowLong32(hWnd, GWL_EXSTYLE, style)); + } + + [StructLayout(LayoutKind.Sequential)] + internal struct RECT + { + internal int Left; + internal int Top; + internal int Right; + internal int Bottom; + + internal Rectangle ToRectangle() + { + return Rectangle.FromLTRB(Left, Top, Right, Bottom); + } + } + + [StructLayout(LayoutKind.Sequential)] + internal struct POINT + { + internal int X; + internal int Y; + + internal POINT(int x, int y) + { + X = x; + Y = y; + } + + 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 new file mode 100644 index 0000000..54ab9cf --- /dev/null +++ b/src/pacs_win_uia/Models/AppSettings.cs @@ -0,0 +1,288 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.Serialization; + +namespace pacs_win_uia.Models +{ + /// + /// 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). + /// + [DataContract] + public sealed class AppSettings + { + public const int CurrentVersion = 1; + + public AppSettings() + { + Ui = new UiSettings(); + FloatingButton = new FloatingButtonSettings(); + Commands = new CommandSettings(); + Ocr = new OcrSettings(); + Read = new ReadSettings(); + } + + [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; } + + [DataMember(Order = 5)] + public OcrSettings Ocr { get; set; } + + [DataMember(Order = 6)] + public ReadSettings Read { get; set; } + + public static AppSettings CreateDefault() + { + var settings = new AppSettings { Version = CurrentVersion }; + settings.Normalize(); + 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. + /// + public void Normalize() + { + Version = CurrentVersion; + if (Ui == null) + { + Ui = new UiSettings(); + } + + if (FloatingButton == null) + { + FloatingButton = new FloatingButtonSettings(); + } + + if (Commands == null) + { + Commands = new CommandSettings(); + } + + if (Ocr == null) + { + Ocr = new OcrSettings(); + } + + if (Read == null) + { + Read = new ReadSettings(); + } + + Ui.TreeMaxDepth = Clamp(Ui.TreeMaxDepth, 1, 32, 12); + Ui.TreeMaxNodes = Clamp(Ui.TreeMaxNodes, 50, 50000, 3000); + Ui.TreeTimeoutSeconds = Clamp(Ui.TreeTimeoutSeconds, 1, 600, 10); + FloatingButton.OpacityPercent = Clamp(FloatingButton.OpacityPercent, 20, 100, 90); + Read.DefaultTimeoutSeconds = Clamp(Read.DefaultTimeoutSeconds, 0, 3600, 10); + + if (Commands.Continuous == null) + { + Commands.Continuous = new List(); + } + + if (Commands.Once == null) + { + Commands.Once = new List(); + } + + foreach (CommandDefinition command in Commands.Continuous) + { + if (command != null) + { + command.IntervalSeconds = Clamp(command.IntervalSeconds, 1, 86400, 60); + } + } + } + + private static int Clamp(int value, int minimum, int maximum, int fallback) + { + if (value == 0) + { + return fallback; + } + + return value < minimum ? minimum : value > maximum ? maximum : value; + } + } + + [DataContract] + public sealed class UiSettings + { + public UiSettings() + { + AutoReadTreeOnSelect = true; + HighlightForegroundWindow = true; + TreeMaxDepth = 12; + TreeMaxNodes = 3000; + TreeTimeoutSeconds = 10; + } + + [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; } + } + + [DataContract] + public sealed class FloatingButtonSettings + { + public FloatingButtonSettings() + { + OpacityPercent = 90; + Actions = new List(); + } + + [DataMember(Order = 1)] + [Description("是否显示悬浮按钮条。它置顶但不抢焦点,可拖动。")] + public bool Enabled { get; set; } + + [DataMember(Order = 2)] + [Description("悬浮条不透明度(20-100)。")] + public int OpacityPercent { get; set; } + + [DataMember(Order = 3)] + [Description("上次的位置 X(保存后下次启动恢复)。")] + public int X { get; set; } + + [DataMember(Order = 4)] + [Description("上次的位置 Y。")] + public int Y { get; set; } + + /// Action ids the toolbar exposes; see FloatingToolbarForm for the known set. + [DataMember(Order = 5)] + public List Actions { get; set; } + } + + [DataContract] + public sealed class CommandSettings + { + [DataMember(Order = 1)] + [Description("工具启动时执行一次的命令行(通过 cmd.exe /c 运行,留空表示不执行)。")] + public string OnStart { get; set; } + + [DataMember(Order = 2)] + [Description("工具退出时执行一次的命令行(留空表示不执行)。")] + public string OnExit { get; set; } + + /// Commands that keep running on an interval while the tool is open. + [DataMember(Order = 3)] + public List Continuous { get; set; } + + /// Commands that run exactly once, when the tool starts. + [DataMember(Order = 4)] + public List Once { get; set; } + } + + [DataContract] + public sealed class CommandDefinition + { + public CommandDefinition() + { + IntervalSeconds = 60; + Enabled = true; + TimeoutSeconds = 30; + } + + [DataMember(Order = 1)] + public string Name { get; set; } + + [DataMember(Order = 2)] + [Description("命令行,通过 cmd.exe /c 执行(可以写一行式命令与管道)。")] + public string CommandLine { get; set; } + + [DataMember(Order = 3)] + [Description("工作目录,留空表示 exe 所在目录。")] + public string WorkingDirectory { get; set; } + + [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 is deliberately not implemented yet: the fields are stored so the shape of the + /// configuration is settled, and the UI says so plainly instead of pretending to work. + /// + [DataContract] + public sealed class OcrSettings + { + public OcrSettings() + { + Language = "zh-CN"; + Engine = "(未实现)"; + } + + [DataMember(Order = 1)] + [Description("是否启用 OCR。**本轮未实现**:勾选也只保存配置,不会执行识别。")] + public bool Enabled { get; set; } + + [DataMember(Order = 2)] + [Description("识别引擎。本轮未实现,预留字段。")] + public string Engine { get; set; } + + [DataMember(Order = 3)] + [Description("识别语言(预留)。")] + public string Language { get; set; } + + [DataMember(Order = 4)] + [Description("截图保存目录(预留)。敏感数据不要上传到外部服务。")] + public string CaptureDirectory { get; set; } + } + + [DataContract] + public sealed class ReadSettings + { + 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 new file mode 100644 index 0000000..55b9a23 --- /dev/null +++ b/src/pacs_win_uia/Models/ControlLocator.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.Serialization; +using System.Text; + +namespace pacs_win_uia.Models +{ + /// Which source a saved control should be re-resolved with. + [DataContract] + public enum ControlSourcePreference + { + /// Try UIA, then MSAA, then Win32; the first that resolves wins. + [EnumMember] + Auto, + + [EnumMember] + Uia, + + [EnumMember] + Msaa, + + [EnumMember] + Win32 + } + + /// One step of the UIA path, from the top-level window down to the control. + [DataContract] + public sealed class ControlLocatorSegment + { + [DataMember(Order = 1, EmitDefaultValue = false)] + public string ControlType { get; set; } + + [DataMember(Order = 2, EmitDefaultValue = false)] + public string Name { get; set; } + + [DataMember(Order = 3, EmitDefaultValue = false)] + public string AutomationId { get; set; } + + /// Ordinal among same-type siblings; the last resort when names are not unique. + [DataMember(Order = 4)] + public int Index { get; set; } + + public override string ToString() + { + string type = string.IsNullOrEmpty(ControlType) ? "?" : ControlType.Replace("ControlType.", string.Empty); + if (!string.IsNullOrEmpty(AutomationId)) + { + return type + "[" + AutomationId + "]"; + } + + return string.IsNullOrEmpty(Name) ? type + "#" + Index : type + ":" + Name; + } + } + + /// One step of the Win32 path: class name plus ordinal among same-class siblings. + [DataContract] + public sealed class Win32LocatorSegment + { + [DataMember(Order = 1, EmitDefaultValue = false)] + public string ClassName { get; set; } + + [DataMember(Order = 2)] + public int Index { get; set; } + + public override string ToString() + { + return (string.IsNullOrEmpty(ClassName) ? "(无类名)" : ClassName) + "#" + Index; + } + } + + /// Helpers shared by the path builder and the resolver so the two cannot disagree. + public static class ControlLocatorFormat + { + /// MSAA path keys are stored relative to the root window ("i3/o1"), not absolute. + public static string StripRoot(string pathKey) + { + if (string.IsNullOrEmpty(pathKey)) + { + return string.Empty; + } + + int slash = pathKey.IndexOf('/'); + return slash < 0 ? string.Empty : pathKey.Substring(slash + 1); + } + + public static IList SplitMsaaPath(string pathKey) + { + var parts = new List(); + string relative = StripRoot(pathKey); + if (string.IsNullOrEmpty(relative)) + { + return parts; + } + + foreach (string part in relative.Split('/')) + { + if (!string.IsNullOrEmpty(part)) + { + parts.Add(part); + } + } + + return parts; + } + + public static string DescribeUiaPath(IList segments) + { + if (segments == null || segments.Count == 0) + { + return string.Empty; + } + + var builder = new StringBuilder(); + foreach (ControlLocatorSegment segment in segments) + { + if (builder.Length > 0) + { + builder.Append(" > "); + } + + builder.Append(segment); + } + + return builder.ToString(); + } + + public static string DescribeWin32Path(IList segments) + { + if (segments == null || segments.Count == 0) + { + return string.Empty; + } + + var builder = new StringBuilder(); + foreach (Win32LocatorSegment segment in segments) + { + if (builder.Length > 0) + { + builder.Append(" > "); + } + + builder.Append(segment); + } + + return builder.ToString(); + } + } + + /// Keys that can be read from a resolved control, per source. + public static class ControlValueKeys + { + /// Cross-source key: is this control the selected one. + public const string Selected = "选中状态"; + + /// Cross-source key: does this control currently have keyboard focus. + public const string Focused = "焦点状态"; + + public static readonly IList Uia = new List + { + "Name", "AutomationId", "ControlType", "ClassName", "FrameworkId", + "RuntimeId", "IsEnabled", "IsOffscreen", "BoundingRectangle", + "Value", "Text", Selected, "IsSelected", Focused, "HasKeyboardFocus" + }; + + public static readonly IList Msaa = new List + { + "accName", "accValue", "accRole", "accState", "accDescription", "accDefaultAction", "PathKey", + Selected, Focused + }; + + public static readonly IList Win32 = new List + { + "窗口标题", "类名", "HWND", "窗口矩形", "客户区矩形", "可见", "最小化", "进程名", "PID", Focused + }; + + /// Suggested keys for a source preference (Auto = the union of all three). + public static IList For(ControlSourcePreference preference) + { + var keys = new List(); + if (preference == ControlSourcePreference.Auto || preference == ControlSourcePreference.Uia) + { + keys.AddRange(Uia); + } + + if (preference == ControlSourcePreference.Auto || preference == ControlSourcePreference.Msaa) + { + keys.AddRange(Msaa); + } + + if (preference == ControlSourcePreference.Auto || preference == ControlSourcePreference.Win32) + { + keys.AddRange(Win32); + } + + return keys; + } + + public static IList ForSource(ControlTreeSource source) + { + switch (source) + { + case ControlTreeSource.Msaa: + return Msaa; + case ControlTreeSource.Win32: + return Win32; + default: + return Uia; + } + } + } +} diff --git a/src/pacs_win_uia/Models/ControlMonitorDefinition.cs b/src/pacs_win_uia/Models/ControlMonitorDefinition.cs new file mode 100644 index 0000000..3c50676 --- /dev/null +++ b/src/pacs_win_uia/Models/ControlMonitorDefinition.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.Serialization; + +namespace pacs_win_uia.Models +{ + [DataContract] + public sealed class ControlMonitorDefinition : IDataErrorInfo + { + public ControlMonitorDefinition() + { + Id = Guid.NewGuid().ToString("N"); + Source = ControlSourcePreference.Auto; + UiaPath = new List(); + Win32Path = new List(); + } + + [DataMember(Order = 1, IsRequired = true)] + public string Id { get; set; } + + /// Human-readable path from the top-level window down to the control. Display only. + [DataMember(Order = 2, IsRequired = true)] + public string ControlPath { get; set; } + + [DataMember(Order = 3, IsRequired = true)] + public string PageFeatures { get; set; } + + [DataMember(Order = 4, IsRequired = true)] + public string ContentKey { get; set; } + + /// + /// 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. + /// + [DataMember(Order = 5, IsRequired = false, EmitDefaultValue = false)] + public string RuntimeId { get; set; } + + // ---------------------------------------------------------------- re-resolution locator + // All of these are additive: a file written by an older build simply has them missing. + + /// + /// 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 + /// write the enum's numeric value and reject the name on read. + /// + [DataMember(Order = 6, Name = "Source", IsRequired = false, EmitDefaultValue = false)] + public string SourceName { get; set; } + + [IgnoreDataMember] + [Description("回读时优先使用的来源:自动(UIA→MSAA→Win32)/ UIA / MSAA / Win32。")] + public ControlSourcePreference Source + { + get { return ParseSourcePreference(SourceName); } + set { SourceName = value.ToString(); } + } + + private static ControlSourcePreference ParseSourcePreference(string value) + { + if (string.IsNullOrEmpty(value)) + { + return ControlSourcePreference.Auto; + } + + // Tolerate a numeric value as well, in case a file was written by an older build. + int numeric; + if (int.TryParse(value, out numeric) && + Enum.IsDefined(typeof(ControlSourcePreference), numeric)) + { + return (ControlSourcePreference)numeric; + } + + try + { + return (ControlSourcePreference)Enum.Parse(typeof(ControlSourcePreference), value, true); + } + catch (ArgumentException) + { + return ControlSourcePreference.Auto; + } + } + + [DataMember(Order = 7, IsRequired = false, EmitDefaultValue = false)] + [Description("目标进程名,用来在不依赖 HWND 的情况下找到顶层窗口。")] + public string ProcessName { get; set; } + + [DataMember(Order = 8, IsRequired = false, EmitDefaultValue = false)] + [Description("顶层窗口类名,配合进程名与标题关键词定位顶层窗口。")] + public string WindowClass { get; set; } + + [DataMember(Order = 9, IsRequired = false, EmitDefaultValue = false)] + [Description("顶层窗口标题关键词(包含匹配)。三个都填时匹配最精确。")] + public string WindowTitleKeyword { get; set; } + + [DataMember(Order = 10, IsRequired = false, EmitDefaultValue = false)] + [Description("UIA 层级定位路径:从顶层窗口到控件逐段记录(AutomationId 优先,其次类型+名称,最后同级序号)。")] + public List UiaPath { get; set; } + + [DataMember(Order = 11, IsRequired = false, EmitDefaultValue = false)] + [Description("MSAA 定位路径,形如 i3/o1/i2(i=简单子 ID,o=子对象),相对于顶层窗口。")] + public string MsaaPathKey { get; set; } + + [DataMember(Order = 12, IsRequired = false, EmitDefaultValue = false)] + [Description("Win32 定位路径:逐级窗口类名 + 同级同类序号。")] + public List Win32Path { get; set; } + + [DataMember(Order = 13, IsRequired = false, EmitDefaultValue = false)] + [Description("要读取的属性名。可选项随来源不同:UIA 用 Name/Value/Text 等,MSAA 用 accName/accValue 等,Win32 用 窗口标题/类名 等。留空表示只定位不取值。")] + public string ValueKey { get; set; } + + /// + /// Stored as "Disabled" so that a config written before this field exists means "enabled": + /// absent must not silently disable every saved control. + /// + [DataMember(Order = 15, Name = "Disabled", IsRequired = false, EmitDefaultValue = false)] + public bool Disabled { get; set; } + + [IgnoreDataMember] + [Description("该条监控是否启用。停用的条目仍保留在配置里,但无界面模式会跳过它。")] + public bool Enabled + { + get { return !Disabled; } + set { Disabled = !value; } + } + + /// + /// Focus state read by the editor's 定位/刷新 action. Not persisted: it describes "right now", + /// not the definition. + /// + [IgnoreDataMember] + [Description("最近一次定位/刷新读到的焦点状态(不保存,只表示当前状态)。")] + public string FocusState { get; set; } + + /// + /// 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 + /// the whole run's budget. + /// + [DataMember(Order = 16, IsRequired = false, EmitDefaultValue = false)] + [Description("等待该控件出现的秒数。0 = 使用全局 --timeout。每条独立计时,某个控件等不到不会拖累其他控件。")] + public int TimeoutSeconds { get; set; } + + [DataMember(Order = 14, IsRequired = false, EmitDefaultValue = false)] + [Description("添加该控件时读到的当前值,供人工核对;回读时以 ValueKey 实时读取的结果为准。")] + public string Value { get; set; } + + string IDataErrorInfo.Error + { + get + { + foreach (string field in ControlMonitorRules.FieldNames) + { + string message = ControlMonitorRules.ValidateField(this, field); + if (message != null) + { + return message; + } + } + + return null; + } + } + + string IDataErrorInfo.this[string columnName] + { + get { return ControlMonitorRules.ValidateField(this, columnName); } + } + + 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 new file mode 100644 index 0000000..0ded6ad --- /dev/null +++ b/src/pacs_win_uia/Models/ControlMonitorRules.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace pacs_win_uia.Models +{ + public sealed class ControlMonitorValidationError + { + public ControlMonitorValidationError(int index, string fieldName, string message) + { + Index = index; + FieldName = fieldName; + Message = message; + } + + /// Index inside the definition list; -1 when the error is about the list itself. + public int Index { get; private set; } + + public string FieldName { get; private set; } + + public string Message { get; private set; } + + public override string ToString() + { + string location = Index < 0 ? "整体" : "第 " + (Index + 1) + " 行"; + return string.IsNullOrEmpty(FieldName) + ? location + ":" + Message + : location + " " + FieldName + ":" + Message; + } + } + + /// + /// 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 + { + public const int MaxDefinitions = 500; + public const int MaxDocumentBytes = 1024 * 1024; + public const int MaxControlPathLength = 2048; + public const int MaxPageFeaturesLength = 512; + public const int MaxContentKeyLength = 128; + public const int MaxRuntimeIdLength = 256; + public const string ContentKeyRule = "^[A-Za-z_][A-Za-z0-9_.-]*$"; + public const int MaxValueKeyLength = 64; + public const int MaxValueLength = 4096; + + private static readonly Regex ContentKeyRegex = new Regex( + @"\A[A-Za-z_][A-Za-z0-9_.-]*\z", RegexOptions.CultureInvariant); + + private static readonly string[] Fields = + { + "Id", + "ControlPath", + "RuntimeId", + "PageFeatures", + "ContentKey", + "ValueKey", + "Value" + }; + + public static IList FieldNames + { + get { return Fields; } + } + + /// Validates one field; returns null when the field is acceptable. + public static string ValidateField(ControlMonitorDefinition definition, string fieldName) + { + if (definition == null) + { + return "定义为空。"; + } + + switch (fieldName) + { + case "Id": + return ValidateId(definition.Id); + case "ControlPath": + return ValidateRequired(definition.ControlPath, "控件 Path", MaxControlPathLength); + case "RuntimeId": + return definition.RuntimeId == null || definition.RuntimeId.Length <= MaxRuntimeIdLength + ? null + : "RuntimeId 过长(上限 " + MaxRuntimeIdLength + " 个字符)。"; + case "PageFeatures": + // Empty means "do not check the page": a control can be located by process and + // path alone. + return definition.PageFeatures == null || definition.PageFeatures.Length <= MaxPageFeaturesLength + ? null + : "所在页面特征过长(上限 " + MaxPageFeaturesLength + " 个字符)。"; + case "ContentKey": + return ValidateContentKey(definition.ContentKey); + case "ValueKey": + // Empty means "locate only, do not read a value"; a filled one must be a sane name. + if (string.IsNullOrEmpty(definition.ValueKey)) + { + return null; + } + + return definition.ValueKey.Length <= MaxValueKeyLength + ? null + : "属性名过长(上限 " + MaxValueKeyLength + " 个字符)。"; + case "Value": + return definition.Value == null || definition.Value.Length <= MaxValueLength + ? null + : "记录的值过长(上限 " + MaxValueLength + " 个字符)。"; + default: + return null; + } + } + + /// Validates the whole list, including rules that span rows. Returns every error found. + public static IList ValidateList(IList definitions) + { + var errors = new List(); + if (definitions == null) + { + errors.Add(new ControlMonitorValidationError(-1, null, "定义列表为空。")); + return errors; + } + + if (definitions.Count > MaxDefinitions) + { + errors.Add(new ControlMonitorValidationError(-1, null, "最多允许 " + MaxDefinitions + " 条控件监控定义。")); + } + + var ids = new HashSet(); + var keys = new HashSet(StringComparer.Ordinal); + long textLength = 0; + for (int index = 0; index < definitions.Count; index++) + { + ControlMonitorDefinition definition = definitions[index]; + if (definition == null) + { + errors.Add(new ControlMonitorValidationError(index, null, "定义不能为空。")); + continue; + } + + foreach (string field in Fields) + { + string message = ValidateField(definition, field); + if (message != null) + { + errors.Add(new ControlMonitorValidationError(index, field, message)); + } + } + + Guid id; + if (Guid.TryParse(definition.Id, out id) && id != Guid.Empty && !ids.Add(id)) + { + errors.Add(new ControlMonitorValidationError(index, "Id", "Id 与其他行重复。")); + } + + if (!string.IsNullOrWhiteSpace(definition.ContentKey) && !keys.Add(definition.ContentKey)) + { + errors.Add(new ControlMonitorValidationError(index, "ContentKey", "别名与其他行重复(区分大小写)。")); + } + + textLength += (long)Length(definition.Id) + Length(definition.ControlPath) + + Length(definition.RuntimeId) + Length(definition.PageFeatures) + Length(definition.ContentKey) + + Length(definition.ProcessName) + Length(definition.WindowClass) + + Length(definition.WindowTitleKeyword) + Length(definition.MsaaPathKey) + + Length(definition.ValueKey) + Length(definition.Value); + if (definition.UiaPath != null) + { + textLength += (long)definition.UiaPath.Count * 64; + } + + if (definition.Win32Path != null) + { + textLength += (long)definition.Win32Path.Count * 64; + } + if (textLength > MaxDocumentBytes) + { + errors.Add(new ControlMonitorValidationError(-1, null, "总内容超过 1 MB 上限,请精简定义。")); + break; + } + } + + return errors; + } + + private static int Length(string value) + { + return value == null ? 0 : value.Length; + } + + private static string ValidateId(string id) + { + Guid parsed; + if (string.IsNullOrWhiteSpace(id) || !Guid.TryParse(id, out parsed) || parsed == Guid.Empty) + { + return "Id 必须是非空 GUID。"; + } + + return null; + } + + private static string ValidateRequired(string value, string label, int maxLength) + { + if (string.IsNullOrWhiteSpace(value)) + { + return label + "不能为空。"; + } + + return value.Length <= maxLength + ? null + : label + "过长(上限 " + maxLength + " 个字符)。"; + } + + private static string ValidateContentKey(string contentKey) + { + if (string.IsNullOrWhiteSpace(contentKey)) + { + return "别名不能为空。"; + } + + if (contentKey.Length > MaxContentKeyLength) + { + return "别名过长(上限 " + MaxContentKeyLength + " 个字符)。"; + } + + if (!ContentKeyRegex.IsMatch(contentKey)) + { + // The key ends up in a JSON document, so it stays ASCII-identifier shaped. + return "别名必须以字母或下划线开头,只能包含字母、数字、下划线、点或连字符(不支持中文)。"; + } + + return null; + } + } +} diff --git a/src/pacs_win_uia/Models/ControlTreeNode.cs b/src/pacs_win_uia/Models/ControlTreeNode.cs new file mode 100644 index 0000000..9d54e73 --- /dev/null +++ b/src/pacs_win_uia/Models/ControlTreeNode.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.Serialization; + +namespace pacs_win_uia.Models +{ + /// + /// Which accessibility source produced a node. The three are independent views of the same UI + /// and are never merged across sources. + /// + [DataContract] + public enum ControlTreeSource + { + [EnumMember] + Uia, + + [EnumMember] + Msaa, + + [EnumMember] + Win32 + } + + /// + /// 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. + /// + [DataContract] + public sealed class ControlTreeNode + { + public ControlTreeNode() + { + Children = new List(); + ChildrenComplete = true; + } + + [DataMember(Order = 1)] + [Description("该节点来自哪个来源:UIA / MSAA / Win32。三个来源是独立视图,不保证互相对应。")] + public ControlTreeSource Source { get; set; } + + /// UIA nodes only: the rich snapshot the rest of the tool already uses. + [DataMember(Order = 2)] + public UiaElementInfo Uia { get; set; } + + /// MSAA nodes only. + [DataMember(Order = 3)] + public MsaaNodeInfo Msaa { get; set; } + + /// Win32 nodes only: HWND, class name, rectangles. + [DataMember(Order = 4)] + public NativeWindowInfo Window { get; set; } + + [DataMember(Order = 5)] + public List Children { get; private set; } + + [DataMember(Order = 6)] + public bool ChildrenComplete { get; set; } + + [DataMember(Order = 7)] + public string ChildrenError { get; set; } + + [Browsable(false)] + [IgnoreDataMember] + public UiaElementInfo UiaElement + { + get { return Source == ControlTreeSource.Uia ? Uia : null; } + } + + /// Tree label. The source is always visible so a Win32-only node cannot be mistaken for a control. + public string Describe() + { + switch (Source) + { + case ControlTreeSource.Msaa: + return "[MSAA] " + (Msaa == null ? "(空)" : Msaa.ToString()); + case ControlTreeSource.Win32: + return DescribeWindow(); + default: + return "[UIA] " + (Uia == null ? "(空)" : Uia.ToString()); + } + } + + private string DescribeWindow() + { + if (Window == null) + { + return "[Win32] (空)"; + } + + var builder = new System.Text.StringBuilder(); + builder.Append("[Win32] ").Append(string.IsNullOrEmpty(Window.ClassName) ? "(无类名)" : Window.ClassName); + if (!string.IsNullOrEmpty(Window.Title)) + { + builder.Append(": ").Append(Window.Title); + } + + builder.Append(" ").Append(Window.HwndHex); + if (!Window.IsVisible) + { + builder.Append(" [隐藏]"); + } + + if (Window.IsMinimized) + { + builder.Append(" [最小化]"); + } + + return builder.ToString(); + } + + public override string ToString() + { + return Describe(); + } + } + + /// Bounds for every reader: no source may run unbounded. + public sealed class ControlTreeOptions + { + public ControlTreeOptions() + { + MaxDepth = 12; + MaxNodes = 3000; + Timeout = TimeSpan.FromSeconds(10); + MaxMsaaChildrenPerNode = 400; + ReadWindowTitles = true; + TitleReadTimeoutMs = 200; + } + + public int MaxDepth { get; set; } + + public int MaxNodes { get; set; } + + public TimeSpan Timeout { get; set; } + + /// Upper bound for one MSAA node's children; huge lists are truncated and flagged. + public int MaxMsaaChildrenPerNode { get; set; } + + /// Window titles need a cross-process WM_GETTEXT; they can be skipped. + public bool ReadWindowTitles { get; set; } + + public int TitleReadTimeoutMs { get; set; } + } +} diff --git a/src/pacs_win_uia/Models/HeadlessReport.cs b/src/pacs_win_uia/Models/HeadlessReport.cs new file mode 100644 index 0000000..058c5d7 --- /dev/null +++ b/src/pacs_win_uia/Models/HeadlessReport.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace pacs_win_uia.Models +{ + /// Result document of one headless (no UI) read of a saved monitor config. + [DataContract] + public sealed class HeadlessReport + { + public HeadlessReport() + { + Windows = new List(); + Items = new List(); + Summary = new HeadlessSummary(); + } + + [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; } + } + + [DataContract] + public sealed class HeadlessSummary + { + [DataMember(Order = 1)] + public int Total { get; set; } + + /// 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; } + + /// 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; } + } + + [DataContract] + public sealed class HeadlessWindowInfo + { + [DataMember(Order = 1)] + public string Hwnd { get; set; } + + [DataMember(Order = 2)] + public string ProcessName { get; set; } + + [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; } + + [DataMember(Order = 4)] + public string RequestedSource { get; set; } + + /// 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; } + + [DataMember(Order = 7)] + public string ValueKey { get; set; } + + [DataMember(Order = 8)] + public string Value { get; set; } + + /// 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; } + } + + [DataContract] + public sealed class HeadlessAttributes + { + [DataMember(Order = 1, EmitDefaultValue = false)] + public string Name { get; set; } + + [DataMember(Order = 2, EmitDefaultValue = false)] + public string ControlType { get; set; } + + [DataMember(Order = 3, EmitDefaultValue = false)] + public string ClassName { get; set; } + + [DataMember(Order = 4, EmitDefaultValue = false)] + public string Role { get; set; } + + [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; } + + [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 new file mode 100644 index 0000000..a38f128 --- /dev/null +++ b/src/pacs_win_uia/Models/ListReadModels.cs @@ -0,0 +1,235 @@ +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, + UiaGridPattern, + UiaTablePattern, + UiaSelectionPattern, + UiaElementTraversal + } + + public enum ListValueSource + { + None, + ValuePattern, + TextPattern, + Name + } + + [DataContract] + public sealed class ListReadOptions + { + public ListReadOptions() + { + MaxRows = 1000; + MaxColumns = 200; + Timeout = TimeSpan.FromSeconds(5); + ReadSelection = true; + MaxErrors = 1000; + MaxTraversalNodes = 5000; + MaxTraversalDepth = 8; + MaxAncestorDepth = 8; + MaxTextLength = 32768; + } + + [DataMember(Order = 1)] + public int MaxRows { get; set; } + + [DataMember(Order = 2)] + public int MaxColumns { get; set; } + + [DataMember(Order = 3)] + public TimeSpan Timeout { get; set; } + + [DataMember(Order = 4)] + public bool ReadSelection { get; set; } + + [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. + [DataMember(Order = 9)] + public int MaxTextLength { get; set; } + } + + [DataContract] + public sealed class ListCellResult + { + [DataMember(Order = 1)] + public int RowIndex { get; set; } + + [DataMember(Order = 2)] + public int ColumnIndex { get; set; } + + [DataMember(Order = 3)] + public string RowId { get; set; } + + [DataMember(Order = 4)] + public string ColumnId { get; set; } + + [DataMember(Order = 5)] + public string Value { get; set; } + + [DataMember(Order = 6)] + public ListValueSource ValueSource { get; set; } + + [DataMember(Order = 7)] + public bool ValueAvailable { get; set; } + + [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(); + } + + [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; } + + [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; } + + [DataMember(Order = 3)] + public string AutomationId { get; set; } + + [DataMember(Order = 4)] + public bool IsAvailable { get; set; } + + [DataMember(Order = 5)] + public string Error { get; set; } + + [DataMember(Order = 6)] + public string RowId { get; set; } + } + + [DataContract] + public sealed class ListReadResult + { + public ListReadResult() + { + ColumnNames = new List(); + Rows = new List(); + SelectedItems = new List(); + Errors = new List(); + Notices = new List(); + ReadAtUtc = DateTime.UtcNow; + Status = ListReadStatus.Unsupported; + Source = ListReadSource.Unknown; + TotalRowsKnown = true; + } + + [DataMember(Order = 1)] + public ListReadStatus Status { get; set; } + + [DataMember(Order = 2)] + public ListReadSource Source { get; set; } + + [DataMember(Order = 3)] + public DateTime ReadAtUtc { get; set; } + + [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; } + + [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; } + + [DataMember(Order = 11)] + public bool IsComplete { get; set; } + + [DataMember(Order = 12)] + public string Error { get; set; } + + [DataMember(Order = 13)] + public List Errors { get; private set; } + + /// + /// 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. + /// + [DataMember(Order = 14)] + public List Notices { get; private set; } + + /// False when RowCount is only "rows realized right now", not a logical total. + [DataMember(Order = 15)] + public bool TotalRowsKnown { get; set; } + + /// How many ancestors above the picked element produced the list; 0 = the picked element itself. + [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 new file mode 100644 index 0000000..5d54757 --- /dev/null +++ b/src/pacs_win_uia/Models/MsaaNodeInfo.cs @@ -0,0 +1,81 @@ +using System.ComponentModel; +using System.Runtime.Serialization; + +namespace pacs_win_uia.Models +{ + /// + /// 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. + /// + [DataContract] + public sealed class MsaaNodeInfo + { + public MsaaNodeInfo() + { + Location = new NativeRectangleInfo(); + RoleId = -1; + } + + /// Synthetic path (root HWND + child ids): MSAA child nodes usually have no HWND. + [DataMember(Order = 1)] + [Description("MSAA 节点的合成路径(根 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 对象)。")] + public int ChildId { get; set; } + + [DataMember(Order = 3)] + [Description("MSAA 名称(accName),列表行的文本通常在这里。")] + public string Name { get; set; } + + [DataMember(Order = 4)] + [Description("MSAA 值(accValue)。很多控件不提供该值,或与 Name 相同。")] + public string Value { get; set; } + + [DataMember(Order = 5)] + [Description("MSAA 角色 ID(ROLE_SYSTEM_*)。")] + public int RoleId { get; set; } + + [DataMember(Order = 6)] + [Description("MSAA 角色名称。列表/列表项/表格这类角色才可能承载列表数据。")] + public string RoleText { get; set; } + + [DataMember(Order = 7)] + [Description("MSAA 状态位(STATE_SYSTEM_*):不可见、屏幕外、已选中、有焦点等。")] + public string StateText { get; set; } + + [DataMember(Order = 8)] + [Description("MSAA 描述(accDescription)。多数控件为空。")] + public string Description { get; set; } + + [DataMember(Order = 9)] + [Description("默认动作名称(accDefaultAction),例如“按下”。只读展示,不会触发。")] + public string DefaultAction { get; set; } + + [DataMember(Order = 10)] + [Description("屏幕位置(accLocation)。MSAA 子节点通常只有这个矩形可用于高亮。")] + public NativeRectangleInfo Location { get; set; } + + [DataMember(Order = 11)] + [Description("该 MSAA 对象是否关联一个原生窗口。只有窗口型对象才有,简单子节点没有。")] + public bool HasWindow { get; set; } + + [DataMember(Order = 12)] + [Description("关联的原生窗口句柄(十进制);为 0 表示没有。")] + public long WindowHandle { get; set; } + + [DataMember(Order = 13)] + [Description("读取该节点时的错误。个别节点失败不影响整棵树。")] + public string Error { get; set; } + + public override string ToString() + { + string role = string.IsNullOrEmpty(RoleText) ? "MSAA" : RoleText; + string name = string.IsNullOrEmpty(Name) ? "(无名称)" : Name; + string value = string.IsNullOrEmpty(Value) ? string.Empty : "(值:" + Value + ")"; + return role + ": " + name + value; + } + } +} diff --git a/src/pacs_win_uia/Models/NativeWindowInfo.cs b/src/pacs_win_uia/Models/NativeWindowInfo.cs new file mode 100644 index 0000000..df0104c --- /dev/null +++ b/src/pacs_win_uia/Models/NativeWindowInfo.cs @@ -0,0 +1,169 @@ +using System; +using System.ComponentModel; +using System.Drawing; +using System.Runtime.Serialization; + +namespace pacs_win_uia.Models +{ + /// + /// A serializable snapshot of the native window information available through Win32. + /// The live HWND is kept separately from the serializable numeric representation. + /// + [DataContract] + public sealed class NativeWindowInfo + { + public NativeWindowInfo(IntPtr handle) + { + Handle = handle; + Hwnd = handle.ToInt64(); + HwndHex = FormatHandle(handle); + WindowBounds = new NativeRectangleInfo(); + ClientBounds = new NativeRectangleInfo(); + } + + [IgnoreDataMember] + [Browsable(false)] + public IntPtr Handle { get; private set; } + + [DataMember(Order = 1)] + public long Hwnd { get; private set; } + + [DataMember(Order = 2)] + public string HwndHex { get; private set; } + + [DataMember(Order = 3)] + public int ProcessId { get; set; } + + [DataMember(Order = 4)] + public string ProcessName { get; set; } + + [DataMember(Order = 5)] + public string Title { get; set; } + + [DataMember(Order = 6)] + public string ClassName { get; set; } + + [DataMember(Order = 7)] + public string ParentHwndHex { get; set; } + + [DataMember(Order = 8)] + public string RootHwndHex { get; set; } + + [DataMember(Order = 9)] + public bool IsVisible { get; set; } + + [DataMember(Order = 10)] + public bool IsMinimized { get; set; } + + [DataMember(Order = 11)] + public bool IsOwnProcess { get; set; } + + [DataMember(Order = 12)] + public NativeRectangleInfo WindowBounds { get; set; } + + [DataMember(Order = 13)] + public NativeRectangleInfo ClientBounds { get; set; } + + [DataMember(Order = 14)] + public string Error { get; set; } + + [Browsable(false)] + [IgnoreDataMember] + public Rectangle WindowRectangle + { + get { return WindowBounds == null ? Rectangle.Empty : WindowBounds.ToRectangle(); } + } + + public override string ToString() + { + string title = string.IsNullOrEmpty(Title) ? "(无标题)" : Title; + string process = string.IsNullOrEmpty(ProcessName) ? "未知进程" : ProcessName; + return string.Format("{0} [{1}] {2}", title, process, HwndHex); + } + + public static string FormatHandle(IntPtr handle) + { + return string.Format("0x{0:X}", handle.ToInt64()); + } + } + + [DataContract] + public sealed class NativeRectangleInfo + { + public NativeRectangleInfo() + { + } + + public NativeRectangleInfo(int left, int top, int right, int bottom) + { + Left = left; + Top = top; + Right = right; + Bottom = bottom; + IsValid = right >= left && bottom >= top; + } + + [DataMember(Order = 1)] + public int Left { get; set; } + + [DataMember(Order = 2)] + public int Top { get; set; } + + [DataMember(Order = 3)] + public int Right { get; set; } + + [DataMember(Order = 4)] + public int Bottom { get; set; } + + [DataMember(Order = 5)] + public bool IsValid { get; set; } + + public int Width + { + get { return IsValid ? Math.Max(0, Right - Left) : 0; } + } + + public int Height + { + get { return IsValid ? Math.Max(0, Bottom - Top) : 0; } + } + + [IgnoreDataMember] + [Browsable(false)] + public Rectangle Rectangle + { + get { return ToRectangle(); } + } + + public Rectangle ToRectangle() + { + if (!IsValid) + { + return Rectangle.Empty; + } + + return Rectangle.FromLTRB(Left, Top, Right, Bottom); + } + + public override string ToString() + { + return IsValid + ? string.Format("({0},{1}) - ({2},{3}) [{4}x{5}]", Left, Top, Right, Bottom, Width, Height) + : "不可用"; + } + + public static NativeRectangleInfo FromRectangle(Rectangle rectangle) + { + if (rectangle.IsEmpty) + { + return new NativeRectangleInfo(); + } + + return new NativeRectangleInfo( + rectangle.Left, + rectangle.Top, + rectangle.Right, + rectangle.Bottom); + } + } +} diff --git a/src/pacs_win_uia/Models/PointPickResult.cs b/src/pacs_win_uia/Models/PointPickResult.cs new file mode 100644 index 0000000..5375ba8 --- /dev/null +++ b/src/pacs_win_uia/Models/PointPickResult.cs @@ -0,0 +1,80 @@ +using System; +using System.Drawing; +using System.Runtime.Serialization; + +namespace pacs_win_uia.Models +{ + [DataContract] + public sealed class PointPickResult + { + [DataMember(Order = 1)] + public int ScreenX { get; set; } + + [DataMember(Order = 2)] + public int ScreenY { get; set; } + + [DataMember(Order = 3)] + public NativeWindowInfo Window { get; set; } + + [DataMember(Order = 4)] + public UiaElementInfo AutomationElement { get; set; } + + [DataMember(Order = 5)] + public bool IsToolWindow { get; set; } + + [DataMember(Order = 6)] + public string FailureReason { get; set; } + + /// Which source actually identified the picked target. + [DataMember(Order = 7)] + public ControlTreeSource PickSource { get; set; } + + /// MSAA hit-test result at the picked point, when MSAA could identify it. + [DataMember(Order = 8)] + public MsaaNodeInfo Msaa { get; set; } + + /// Deepest child window at the point (Win32 answer; the renderer window for a browser shell). + [DataMember(Order = 9)] + public NativeWindowInfo DeepestWindow { get; set; } + + /// Rectangle used for highlighting, whichever source produced it. + [DataMember(Order = 10)] + public NativeRectangleInfo Bounds { get; set; } + + /// + /// 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. + /// + [DataMember(Order = 11)] + public bool IsWindowOnlyPick { get; set; } + + [IgnoreDataMember] + public bool HasBounds + { + get { return Bounds != null && Bounds.IsValid; } + } + + [IgnoreDataMember] + public Point ScreenPoint + { + get { return new Point(ScreenX, ScreenY); } + set + { + ScreenX = value.X; + ScreenY = value.Y; + } + } + + [IgnoreDataMember] + public bool HasNativeWindow + { + get { return Window != null && Window.Handle != IntPtr.Zero; } + } + + [IgnoreDataMember] + public bool HasAutomationElement + { + get { return AutomationElement != null && AutomationElement.IsAvailable; } + } + } +} diff --git a/src/pacs_win_uia/Models/UiaElementInfo.cs b/src/pacs_win_uia/Models/UiaElementInfo.cs new file mode 100644 index 0000000..94cf902 --- /dev/null +++ b/src/pacs_win_uia/Models/UiaElementInfo.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Runtime.Serialization; +using System.Windows.Automation; + +namespace pacs_win_uia.Models +{ + /// + /// A safe snapshot of an AutomationElement. AutomationElement itself is intentionally not serialized. + /// + [DataContract] + public sealed class UiaElementInfo + { + public UiaElementInfo() + { + SupportedPatterns = new List(); + PropertyErrors = new List(); + BoundingRectangle = new NativeRectangleInfo(); + } + + [IgnoreDataMember] + [Browsable(false)] + public AutomationElement Element { get; set; } + + [DataMember(Order = 1)] + [Description("UIA 名称。按钮文字、列表行的文本通常在这里;为空不代表控件没有内容,可能要从 ValuePattern/TextPattern 取。")] + public string Name { get; set; } + + [DataMember(Order = 2)] + [Description("控件在程序内部的 AutomationId。通常比 Name 稳定,适合用来定位要监控的控件。")] + public string AutomationId { get; set; } + + [DataMember(Order = 3)] + [Description("UIA 控件类型,决定这个控件支持哪些模式(Pattern)。列表必须是 List/DataGrid/Table/Tree 这类容器类型。")] + public string ControlType { get; set; } + + [DataMember(Order = 4)] + [Description("Win32 窗口类名。Chrome_WidgetWin_1 = Chromium/CEF 内核;WindowsForms10.* = WinForms;HwndWrapper* = WPF。")] + public string ClassName { get; set; } + + [DataMember(Order = 5)] + [Description("无障碍提供者框架:Win32 / WinForm / WPF / UIA。框架不同,能读到的信息差别很大。")] + public string FrameworkId { get; set; } + + [DataMember(Order = 6)] + [Description("原生窗口句柄(十进制)。为 0 表示这是一个没有独立窗口的元素(自绘/无窗口控件)。")] + public long NativeWindowHandle { get; set; } + + [DataMember(Order = 7)] + [Description("控件当前是否可用(未禁用)。")] + public bool? IsEnabled { get; set; } + + [DataMember(Order = 8)] + [Description("控件是否在屏幕外:被滚动出可视区域、已折叠或已隐藏。遍历降级读取时这些行读不到。")] + public bool? IsOffscreen { get; set; } + + [DataMember(Order = 9)] + [Description("控件在屏幕上的矩形(像素)。高亮框和拾取定位都用它。")] + public NativeRectangleInfo BoundingRectangle { get; set; } + + [DataMember(Order = 10)] + [Description("所属进程 ID。跨进程读取可能变慢或卡住;权限较低时也读不到更高权限的进程。")] + public int ProcessId { get; set; } + + [DataMember(Order = 11)] + public string ProviderDescription { get; set; } + + [DataMember(Order = 12)] + [Description("本次快照是否成功读到了这个元素。为 False 时下面的 Error 会说明原因。")] + public bool IsAvailable { get; set; } + + [DataMember(Order = 13)] + [Description("读取失败的原因。ElementNotAvailable 通常表示控件已经销毁或被重建。")] + public string Error { get; set; } + + [DataMember(Order = 14)] + [Description("该元素支持的 UIA 模式列表。读取列表依赖 GridPattern/TablePattern/SelectionPattern;没有这些模式时会走子元素遍历降级。")] + public List SupportedPatterns { get; private set; } + + [DataMember(Order = 15)] + [Description("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. + /// + public void EnsureRuntimeId() + { + if (!string.IsNullOrEmpty(RuntimeId) || Element == null) + { + return; + } + + try + { + int[] id = Element.GetRuntimeId(); + if (id != null && id.Length > 0) + { + RuntimeId = string.Join(".", Array.ConvertAll(id, value => value.ToString())); + } + } + catch (Exception ex) + { + PropertyErrors.Add("RuntimeId: " + ex.GetType().Name + ": " + ex.Message); + } + } + + [DataMember(Order = 16)] + [Description("逐个属性读取失败的记录(某个 Provider 拒绝某个属性时不会让整个快照失败)。")] + public List PropertyErrors { get; private set; } + + [DataMember(Order = 17)] + [Description("该控件当前是否有键盘焦点(UIA HasKeyboardFocus)。用于监控“现在焦点在哪个控件”,与“是否被选中”不是一回事。")] + public bool? HasKeyboardFocus { get; set; } + + [DataMember(Order = 18)] + [Description("该控件是否可以获得键盘焦点(UIA IsKeyboardFocusable)。不能获得焦点的控件,焦点状态永远是“否”。")] + public bool? IsKeyboardFocusable { get; set; } + + [Browsable(false)] + [IgnoreDataMember] + public Rectangle BoundingRectangleValue + { + get { return BoundingRectangle == null ? Rectangle.Empty : BoundingRectangle.ToRectangle(); } + } + + public override string ToString() + { + string type = string.IsNullOrEmpty(ControlType) ? "未知控件" : ControlType; + string name = string.IsNullOrEmpty(Name) ? "(无名称)" : Name; + return string.Format("{0}: {1}", type, name); + } + } + + [DataContract] + public sealed class UiaTreeNodeInfo + { + public UiaTreeNodeInfo() + { + Children = new List(); + } + + [DataMember(Order = 1)] + public UiaElementInfo Element { get; set; } + + [DataMember(Order = 2)] + public List Children { get; private set; } + + [DataMember(Order = 3)] + public bool ChildrenComplete { get; set; } + + [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 new file mode 100644 index 0000000..3d793f1 --- /dev/null +++ b/src/pacs_win_uia/Models/WindowEnumerationResult.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace pacs_win_uia.Models +{ + [DataContract] + public sealed class WindowEnumerationResult + { + public WindowEnumerationResult() + { + Windows = new List(); + } + + [DataMember(Order = 1)] + public bool Succeeded { get; set; } + + [DataMember(Order = 2)] + public string Error { get; set; } + + [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 new file mode 100644 index 0000000..63b3079 --- /dev/null +++ b/src/pacs_win_uia/Picker/CrosshairPicker.cs @@ -0,0 +1,383 @@ +using System; +using System.Drawing; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Models; +using pacs_win_uia.Services; +using pacs_win_uia.UI; + +namespace pacs_win_uia.Picker +{ + /// + /// Coordinates the non-invasive crosshair overlay, target probing and highlighting. + /// + public sealed class CrosshairPicker : IDisposable + { + private static readonly TimeSpan ProbeStuckThreshold = TimeSpan.FromSeconds(2); + private static readonly TimeSpan PickWaitTimeout = TimeSpan.FromSeconds(1.2); + private readonly Control _owner; + private readonly TargetProbeService _probeService; + private readonly HighlightOverlayForm _highlight; + private readonly System.Windows.Forms.Timer _probeWatchdog; + private PickerOverlayForm _pickerOverlay; + private CancellationTokenSource _operationCancellation; + private bool _isPicking; + private int _probeSequence; + private Point _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; + private DateTime _probeStartedUtc; + private DateTime _pickDeadlineUtc; + + public CrosshairPicker(Control owner, TargetProbeService probeService) + { + _owner = owner ?? throw new ArgumentNullException("owner"); + _probeService = probeService ?? throw new ArgumentNullException("probeService"); + _highlight = new HighlightOverlayForm(); + // Fine-grained enough to honour the pick deadline (1.2 s) without being busy. + _probeWatchdog = new System.Windows.Forms.Timer { Interval = 150 }; + _probeWatchdog.Tick += ProbeWatchdogOnTick; + } + + public bool IsPicking + { + get { return _isPicking; } + } + + public event EventHandler PreviewChanged; + public event EventHandler Picked; + public event EventHandler Canceled; + + public void Start() + { + if (_isPicking || _owner.IsDisposed) + { + return; + } + + _isPicking = true; + _highlight.HideHighlight(); + _hasLastProbePoint = false; + _lastNativeWindowHandle = IntPtr.Zero; + _hasPendingProbePoint = false; + _pickRequested = false; + _lastResult = null; + _probeTask = null; + _operationCancellation = new CancellationTokenSource(); + _pickerOverlay = new PickerOverlayForm(); + _pickerOverlay.EscapePressed += PickerOverlayOnEscapePressed; + _pickerOverlay.LeftButtonReleased += PickerOverlayOnLeftButtonReleased; + _pickerOverlay.CursorMoved += PickerOverlayOnCursorMoved; + _pickerOverlay.FormClosed += PickerOverlayOnFormClosed; + _pickerOverlay.Show(); + _probeWatchdog.Start(); + AppLog.Info("十字拾取器已启动。"); + } + + /// + /// 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. + /// + private void ProbeWatchdogOnTick(object sender, EventArgs e) + { + if (!_isPicking) + { + return; + } + + if (_pickRequested && DateTime.UtcNow >= _pickDeadlineUtc) + { + // The click is honoured with the information that is actually available: a Win32 + // window lookup is synchronous and cannot hang. Never leave the overlay up. + AppLog.Warn("拾取确认:UIA 探测未在 " + PickWaitTimeout.TotalSeconds + + " 秒内返回,改为按 Win32 窗口信息确认目标。"); + PointPickResult fallback = _probeService.ProbeWindowOnly(_pickPoint, _lastNativeWindowHandle); + FinishPick(fallback, false); + return; + } + + if (_probeTask == null || _probeTask.IsCompleted) + { + return; + } + + if (DateTime.UtcNow - _probeStartedUtc < ProbeStuckThreshold) + { + return; + } + + AppLog.Warn("拾取预览:单次探测超过 " + ProbeStuckThreshold.TotalSeconds + " 秒未返回,已放弃并在下次鼠标移动时重试。"); + _probeSequence++; + _probeTask = null; + // A pending pick keeps its own deadline: dropping it here would swallow the click. + if (!_pickRequested) + { + _hasPendingProbePoint = false; + _highlight.HideHighlight(); + } + } + + public void Cancel() + { + if (!_isPicking) + { + return; + } + + AppLog.Info("十字拾取已取消。"); + Stop(false); + EventHandler handler = Canceled; + if (handler != null) + { + handler(this, EventArgs.Empty); + } + } + + private void PickerOverlayOnCursorMoved(object sender, CursorPositionEventArgs e) + { + if (!_isPicking || _operationCancellation == null) + { + return; + } + + _lastNativeWindowHandle = e.WindowHandle; + Point screenPoint = e.ScreenPoint; + if (_hasLastProbePoint && _lastProbePoint == screenPoint) + { + return; + } + + _lastProbePoint = screenPoint; + _hasLastProbePoint = true; + if (_probeTask != null && !_probeTask.IsCompleted) + { + _pendingProbePoint = screenPoint; + _hasPendingProbePoint = true; + return; + } + + StartProbe(screenPoint); + } + + private void StartProbe(Point screenPoint) + { + if (!_isPicking || _operationCancellation == null) + { + return; + } + + int sequence = ++_probeSequence; + CancellationToken token = _operationCancellation.Token; + _probeStartedUtc = DateTime.UtcNow; + _probeTask = _probeService.ProbeAsync(screenPoint, token, _lastNativeWindowHandle); + _probeTask.ContinueWith( + task => CompletePreview(sequence, screenPoint, task), + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.FromCurrentSynchronizationContext()); + } + + private void CompletePreview(int sequence, Point probedPoint, Task task) + { + if (!_isPicking || sequence != _probeSequence) + { + return; + } + + _probeTask = null; + if (task.IsCanceled) + { + _pickRequested = false; + _hasPendingProbePoint = false; + return; + } + + if (task.IsFaulted) + { + task.Exception.Handle(delegate { return true; }); + _pickRequested = false; + _hasPendingProbePoint = false; + _highlight.HideHighlight(); + return; + } + if (!task.IsCanceled && !task.IsFaulted) + { + _lastResult = task.Result; + bool hasHighlight = false; + + // Bounds is filled from whichever source identified the target, so a target that only + // Win32 or MSAA can see still gets a highlight box. + if (_lastResult != null && _lastResult.HasBounds) + { + _highlight.ShowHighlight(_lastResult.Bounds.ToRectangle()); + hasHighlight = true; + } + + if (!hasHighlight) + { + _highlight.HideHighlight(); + } + + EventHandler previewHandler = PreviewChanged; + if (previewHandler != null) + { + previewHandler(this, _lastResult); + } + } + + if (_pickRequested) + { + if (probedPoint == _pickPoint && !task.IsCanceled && !task.IsFaulted) + { + FinishPick(task.Result); + return; + } + + _pendingProbePoint = _pickPoint; + _hasPendingProbePoint = true; + } + + if (_hasPendingProbePoint) + { + Point nextPoint = _pendingProbePoint; + _hasPendingProbePoint = false; + StartProbe(nextPoint); + } + } + + private void PickerOverlayOnEscapePressed(object sender, EventArgs e) + { + Cancel(); + } + + private void PickerOverlayOnLeftButtonReleased(object sender, EventArgs e) + { + if (!_isPicking) + { + return; + } + + _pickPoint = Cursor.Position; + _lastNativeWindowHandle = _pickerOverlay == null + ? IntPtr.Zero + : _pickerOverlay.RefreshCurrentWindowHandle(_pickPoint); + _pickRequested = true; + _pickDeadlineUtc = DateTime.UtcNow + PickWaitTimeout; + _lastResult = null; + + _pendingProbePoint = _pickPoint; + _hasPendingProbePoint = true; + if (_probeTask == null || _probeTask.IsCompleted) + { + Point nextPoint = _pendingProbePoint; + _hasPendingProbePoint = false; + StartProbe(nextPoint); + } + } + + private void FinishPick(PointPickResult result) + { + FinishPick(result, true); + } + + /// + /// 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. + /// + private void FinishPick(PointPickResult result, bool allowRetryWhenInvalid) + { + if (result == null || result.IsToolWindow || !result.HasNativeWindow) + { + AppLog.Warn("拾取确认无效:" + (result == null ? "无探测结果" : result.FailureReason ?? "目标无效")); + _pickRequested = false; + _hasPendingProbePoint = false; + _highlight.HideHighlight(); + if (allowRetryWhenInvalid) + { + EventHandler invalidHandler = PreviewChanged; + if (invalidHandler != null) + { + invalidHandler(this, result); + } + + return; + } + + Stop(false); + EventHandler failedHandler = Picked; + if (failedHandler != null) + { + failedHandler(this, result); + } + + return; + } + + AppLog.Info("拾取确认:HWND=" + result.Window.HwndHex + + ";UIA=" + (result.AutomationElement == null ? "无" : result.AutomationElement.ToString())); + _pickRequested = false; + Stop(true); + EventHandler handler = Picked; + if (handler != null) + { + handler(this, result); + } + } + + private void PickerOverlayOnFormClosed(object sender, FormClosedEventArgs e) + { + if (_isPicking) + { + Stop(false); + } + } + + private void Stop(bool keepHighlight) + { + _isPicking = false; + _probeWatchdog.Stop(); + _probeSequence++; + _hasPendingProbePoint = false; + _pickRequested = false; + if (_operationCancellation != null) + { + _operationCancellation.Cancel(); + _operationCancellation.Dispose(); + _operationCancellation = null; + } + _probeTask = null; + + if (_pickerOverlay != null) + { + _pickerOverlay.EscapePressed -= PickerOverlayOnEscapePressed; + _pickerOverlay.LeftButtonReleased -= PickerOverlayOnLeftButtonReleased; + _pickerOverlay.CursorMoved -= PickerOverlayOnCursorMoved; + _pickerOverlay.FormClosed -= PickerOverlayOnFormClosed; + _pickerOverlay.Close(); + _pickerOverlay.Dispose(); + _pickerOverlay = null; + } + + if (!keepHighlight) + { + _highlight.HideHighlight(); + } + } + + public void Dispose() + { + Stop(false); + _probeWatchdog.Tick -= ProbeWatchdogOnTick; + _probeWatchdog.Dispose(); + _highlight.Dispose(); + } + } +} diff --git a/src/pacs_win_uia/Program.cs b/src/pacs_win_uia/Program.cs new file mode 100644 index 0000000..3966a71 --- /dev/null +++ b/src/pacs_win_uia/Program.cs @@ -0,0 +1,260 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Threading; +using System.Windows.Forms; +using System.Xml; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Models; +using pacs_win_uia.Services; + +namespace pacs_win_uia +{ + internal static class Program + { + private const string Usage = + "用法:\r\n" + + " pacs_win_uia.exe 打开界面(默认)\r\n" + + " pacs_win_uia.exe --read-saved 读取界面保存的配置,结果写到 exe 目录的 out.json\r\n" + + " pacs_win_uia.exe --read-config [配置文件] [选项] 无界面读取并输出 JSON\r\n" + + "\r\n" + + "选项:\r\n" + + " --output [文件] 把 JSON 写到文件;省略路径时写到 exe 目录的 out.json;" + + "给 --output 但不是文件路径时输出到标准输出\r\n" + + " --timeout <秒> 等待目标窗口出现的秒数,默认 10,0 表示不等待\r\n" + + " --activate 读取前先尝试激活目标无障碍(实验性,会改变目标程序状态)\r\n" + + " --help 显示本帮助\r\n" + + "\r\n" + + "默认路径:\r\n" + + " 配置: %LocalAppData%\\pacs_win_uia\\control-monitors.json(界面“保存”的位置)\r\n" + + " 输出: \\out.json(从 bin\\Debug 运行就是 bin\\Debug\\out.json)\r\n" + + "\r\n" + + "退出码: 0=全部命中;1=有未命中或取不到值;2=参数或配置错误"; + + [STAThread] + private static int Main(string[] args) + { + AppLog.Init(); + AppLog.Info("pacs_win_uia 启动;只读模式,不注入目标进程。"); + AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; + Application.ThreadException += OnThreadException; + Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); + + if (args != null && args.Length > 0) + { + return RunHeadless(args); + } + + try + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + return 0; + } + catch (Exception ex) + { + AppLog.Error("主界面异常退出。", ex); + throw; + } + finally + { + AppLog.Info("pacs_win_uia 退出。"); + } + } + + private static int RunHeadless(string[] args) + { + string configPath = null; + string outputPath = null; + double timeoutSeconds = 10; + bool activate = false; + + for (int index = 0; index < args.Length; index++) + { + string arg = args[index]; + switch (arg) + { + case "--help": + case "-h": + case "/?": + Console.WriteLine(Usage); + return 0; + case "--read-config": + // The path is optional: without one the config the GUI saved is used. + if (index + 1 < args.Length && !args[index + 1].StartsWith("--", StringComparison.Ordinal)) + { + configPath = args[++index]; + } + else + { + configPath = GetDefaultConfigPath(); + } + + break; + case "--read-saved": + configPath = GetDefaultConfigPath(); + outputPath = GetDefaultOutputPath(); + break; + case "--output": + if (index + 1 < args.Length && !args[index + 1].StartsWith("--", StringComparison.Ordinal)) + { + outputPath = args[++index]; + } + else + { + outputPath = GetDefaultOutputPath(); + } + + break; + case "--timeout": + if (++index >= args.Length || !double.TryParse(args[index], out timeoutSeconds) || timeoutSeconds < 0) + { + return UsageError("--timeout 需要一个不小于 0 的秒数。"); + } + + break; + case "--activate": + activate = true; + break; + default: + return UsageError("无法识别的参数:" + arg); + } + } + + if (string.IsNullOrEmpty(configPath)) + { + return UsageError("必须指定 --read-config 或 --read-saved。"); + } + + string fullConfigPath; + try + { + fullConfigPath = Path.GetFullPath(configPath); + } + catch (Exception ex) + { + return UsageError("配置文件路径无效:" + ex.Message); + } + + if (!File.Exists(fullConfigPath)) + { + return UsageError("配置文件不存在:" + fullConfigPath); + } + + Console.Error.WriteLine("配置文件:" + fullConfigPath); + if (!string.IsNullOrEmpty(outputPath)) + { + Console.Error.WriteLine("输出文件:" + Path.GetFullPath(outputPath)); + } + + HeadlessReport report; + try + { + var reader = new HeadlessConfigReader(new ControlMonitorStore(fullConfigPath)); + report = reader.Read(fullConfigPath, TimeSpan.FromSeconds(timeoutSeconds), activate, CancellationToken.None); + } + catch (InvalidDataException ex) + { + // A malformed config is a usage problem, not a read failure. + AppLog.Error("配置文件无效。", ex); + Console.Error.WriteLine("配置文件无效:" + ex.Message); + return 2; + } + catch (Exception ex) + { + AppLog.Error("无界面读取失败。", ex); + Console.Error.WriteLine("无界面读取失败:" + ex.Message); + return 2; + } + + try + { + string json = SerializeReport(report); + if (string.IsNullOrEmpty(outputPath)) + { + Console.Out.WriteLine(json); + } + else + { + string fullOutput = Path.GetFullPath(outputPath); + string directory = Path.GetDirectoryName(fullOutput); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + File.WriteAllText(fullOutput, json, new UTF8Encoding(false)); + AppLog.Info("报告已写入:" + fullOutput); + Console.Out.WriteLine("报告已写入:" + fullOutput); + } + } + catch (Exception ex) + { + AppLog.Error("写出报告失败。", ex); + Console.Error.WriteLine("写出报告失败:" + ex.Message); + return 2; + } + + bool allRead = report.Summary.Total > 0 && + report.Summary.Missing == 0 && + report.Summary.ValueUnavailable == 0; + return allRead ? 0 : 1; + } + + /// The config the GUI writes to by default. + private static string GetDefaultConfigPath() + { + string directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return Path.Combine(directory, "pacs_win_uia", "control-monitors.json"); + } + + /// out.json next to the executable, so running from bin\\Debug writes there. + private static string GetDefaultOutputPath() + { + string exeDirectory = Path.GetDirectoryName(typeof(Program).Assembly.Location); + return Path.Combine( + string.IsNullOrEmpty(exeDirectory) ? Directory.GetCurrentDirectory() : exeDirectory, + "out.json"); + } + + private static string SerializeReport(HeadlessReport report) + { + var serializer = new DataContractJsonSerializer(typeof(HeadlessReport)); + using (var stream = new MemoryStream()) + { + using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter( + stream, new UTF8Encoding(false), false, true)) + { + serializer.WriteObject(writer, report); + writer.Flush(); + } + + return new UTF8Encoding(false).GetString(stream.ToArray()); + } + } + + private static int UsageError(string message) + { + Console.Error.WriteLine(message); + Console.Error.WriteLine(); + Console.Error.WriteLine(Usage); + AppLog.Error("参数错误:" + message); + return 2; + } + + private static void OnThreadException(object sender, ThreadExceptionEventArgs e) + { + AppLog.Error("界面线程未处理异常。", e.Exception); + } + + private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) + { + AppLog.Error( + "未处理异常;即将终止:" + e.IsTerminating, + e.ExceptionObject as Exception); + } + } +} diff --git a/src/pacs_win_uia/Properties/AssemblyInfo.cs b/src/pacs_win_uia/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..bfcc066 --- /dev/null +++ b/src/pacs_win_uia/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("pacs_win_uia")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("pacs_win_uia")] +[assembly: AssemblyCopyright("Copyright © 2026")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/src/pacs_win_uia/Services/AccessibilityActivationService.cs b/src/pacs_win_uia/Services/AccessibilityActivationService.cs new file mode 100644 index 0000000..d6d8045 --- /dev/null +++ b/src/pacs_win_uia/Services/AccessibilityActivationService.cs @@ -0,0 +1,176 @@ +using System; +using System.Threading; +using System.Windows.Automation; +using pacs_win_uia.Diagnostics; + +namespace pacs_win_uia.Services +{ + /// + /// Experimental: ask a target to turn on its accessibility support. + /// + /// Chromium/CEF/Electron/WebView2 build their accessibility tree only once they detect an + /// assistive client. Two triggers are used here: an MSAA query on the window (WM_GETOBJECT with + /// OBJID_CLIENT) and registering a UIA event handler, which makes UiaClientsAreListening() true. + /// + /// This changes state inside the target application, it is provider specific, and it is not + /// guaranteed to work — the UI must keep it opt-in and report the outcome honestly. + /// + public sealed class AccessibilityActivationService : IDisposable + { + private readonly object _sync = new object(); + private readonly MsaaService _msaa = new MsaaService(); + private AutomationFocusChangedEventHandler _handler; + private Thread _listenerThread; + private volatile bool _listening; + + 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(); + + if (handle != IntPtr.Zero) + { + object accessible; + string error; + if (_msaa.TryGetRoot(handle, out accessible, out error)) + { + parts.Add("已对目标窗口发起 MSAA 查询(WM_GETOBJECT)"); + if (accessible != null) + { + try + { + System.Runtime.InteropServices.Marshal.ReleaseComObject(accessible); + } + catch (Exception) + { + // Best effort. + } + } + } + else + { + parts.Add("MSAA 查询未成功(" + error + ")"); + } + } + + StartListening(); + parts.Add(_listening + ? "已注册 UIA 事件监听(使 UiaClientsAreListening() 为真)" + : "UIA 事件监听未启动"); + + string summary = string.Join(";", parts.ToArray()) + "。请等待约 1 秒后重新读取控件树。"; + AppLog.Info("尝试激活目标无障碍:" + summary); + return summary; + } + + /// + /// The registration must stay alive for the flag to remain true, so it lives on its own + /// 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. + /// + public void StartListening() + { + lock (_sync) + { + if (_listening) + { + return; + } + + _listening = true; + _listenerThread = new Thread(ListenLoop) + { + IsBackground = true, + Name = "pacs-uia-activation-listener" + }; + _listenerThread.SetApartmentState(ApartmentState.MTA); + _listenerThread.Start(); + } + } + + public void StopListening() + { + Thread thread; + lock (_sync) + { + if (!_listening) + { + return; + } + + _listening = false; + thread = _listenerThread; + _listenerThread = null; + } + + if (thread != null) + { + try + { + thread.Join(TimeSpan.FromSeconds(2)); + } + catch (Exception ex) + { + AppLog.Warn("等待 UIA 监听线程退出失败。", ex); + } + } + } + + private void ListenLoop() + { + try + { + _handler = OnFocusChanged; + Automation.AddAutomationFocusChangedEventHandler(_handler); + AppLog.Info("UIA 焦点事件监听已注册(" + Thread.CurrentThread.GetApartmentState() + " 线程)。"); + } + catch (Exception ex) + { + AppLog.Error("注册 UIA 焦点事件监听失败(激活可能无效)。", ex); + return; + } + + try + { + while (_listening) + { + Thread.Sleep(200); + } + } + catch (Exception) + { + // Falls through to the removal below. + } + + try + { + Automation.RemoveAutomationFocusChangedEventHandler(_handler); + AppLog.Info("UIA 焦点事件监听已注销。"); + } + catch (Exception ex) + { + AppLog.Warn("注销 UIA 焦点事件监听失败。", ex); + } + finally + { + _handler = null; + } + } + + 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 new file mode 100644 index 0000000..2740fb4 --- /dev/null +++ b/src/pacs_win_uia/Services/AppSettingsStore.cs @@ -0,0 +1,188 @@ +using System; +using System.IO; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Xml; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// 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. + /// If the exe folder is not writable the store falls back to the per-user folder instead of + /// failing. + /// + public sealed class AppSettingsStore + { + public const string FileName = "settings.json"; + + private const int MaxFileBytes = 256 * 1024; + + private readonly string _preferredPath; + private readonly string _fallbackPath; + private string _activePath; + + public AppSettingsStore() + : this(GetExeDirectoryPath(), GetUserDirectoryPath()) + { + } + + public AppSettingsStore(string preferredPath, string fallbackPath) + { + _preferredPath = preferredPath ?? throw new ArgumentNullException("preferredPath"); + _fallbackPath = fallbackPath ?? throw new ArgumentNullException("fallbackPath"); + _activePath = _preferredPath; + } + + /// Where the settings were actually read from / written to. + public string FilePath + { + get { return _activePath; } + } + + 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. + /// + public AppSettings Load() + { + AppSettings settings = null; + _activePath = _preferredPath; + if (!File.Exists(_preferredPath) && File.Exists(_fallbackPath)) + { + // A previous run could only write to the user folder. + _activePath = _fallbackPath; + } + + if (File.Exists(_activePath)) + { + try + { + settings = ReadFile(_activePath); + } + catch (Exception ex) + { + AppLog.Error("设置文件无法解析,已改用默认设置(原文件保留):" + _activePath, ex); + settings = null; + } + } + + if (settings == null) + { + settings = AppSettings.CreateDefault(); + if (!File.Exists(_activePath)) + { + AppLog.Info("没有设置文件,已生成默认设置:" + _activePath); + Save(settings); + } + } + else + { + AppLog.Info("已加载设置:" + _activePath); + } + + settings.Normalize(); + return settings; + } + + public bool Save(AppSettings settings) + { + if (settings == null) + { + throw new ArgumentNullException("settings"); + } + + settings.Normalize(); + byte[] data; + using (var stream = new MemoryStream()) + { + using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter( + stream, new UTF8Encoding(false), false, true)) + { + new DataContractJsonSerializer(typeof(AppSettings)).WriteObject(writer, settings); + writer.Flush(); + } + + data = stream.ToArray(); + } + + if (TryWrite(_preferredPath, data)) + { + _activePath = _preferredPath; + return true; + } + + if (TryWrite(_fallbackPath, data)) + { + _activePath = _fallbackPath; + AppLog.Warn("exe 目录不可写,设置已写到:" + _fallbackPath); + return true; + } + + AppLog.Error("设置保存失败:两个位置都不可写(" + _preferredPath + " / " + _fallbackPath + ")。"); + return false; + } + + private static AppSettings ReadFile(string path) + { + var info = new FileInfo(path); + if (info.Length > MaxFileBytes) + { + throw new InvalidDataException("设置文件超过 256 KB 上限。"); + } + + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader( + stream, new XmlDictionaryReaderQuotas { MaxDepth = 16, MaxStringContentLength = MaxFileBytes })) + { + return (AppSettings)new DataContractJsonSerializer(typeof(AppSettings)).ReadObject(reader); + } + } + + private static bool TryWrite(string path, byte[] data) + { + try + { + string directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + File.WriteAllBytes(path, data); + return true; + } + catch (Exception ex) + { + AppLog.Warn("写入设置失败:" + path + ";" + ex.GetType().Name + ": " + ex.Message); + return false; + } + } + + private static string GetExeDirectoryPath() + { + string directory = Path.GetDirectoryName(typeof(AppSettingsStore).Assembly.Location); + return Path.Combine( + string.IsNullOrEmpty(directory) ? Directory.GetCurrentDirectory() : directory, + FileName); + } + + private static string GetUserDirectoryPath() + { + string directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return Path.Combine(directory, "pacs_win_uia", FileName); + } + } +} diff --git a/src/pacs_win_uia/Services/CommandRunner.cs b/src/pacs_win_uia/Services/CommandRunner.cs new file mode 100644 index 0000000..9fd3a11 --- /dev/null +++ b/src/pacs_win_uia/Services/CommandRunner.cs @@ -0,0 +1,321 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading; +using System.Windows.Forms; +using pacs_win_uia.Diagnostics; +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; + Text = text; + IsError = isError; + } + + public string Name { get; private set; } + + public string Text { get; private set; } + + 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(只在启动时跑一次)。 + /// + /// Commands run as the current user through cmd.exe /c. The tool still never injects into the + /// target process and never elevates; command output is logged as-is, so operators must not put + /// patient data on a command line. + /// + public sealed class CommandRunner : IDisposable + { + private readonly object _sync = new object(); + private readonly List _continuousTimers = new List(); + private readonly HashSet _inFlight = new HashSet(StringComparer.Ordinal); + private bool _disposed; + + public event EventHandler Output; + + public bool IsContinuousRunning + { + get + { + lock (_sync) + { + return _continuousTimers.Count > 0; + } + } + } + + public void RunStartCommands(AppSettings settings) + { + if (settings == null || settings.Commands == null) + { + return; + } + + RunSimple("启动", settings.Commands.OnStart); + foreach (CommandDefinition command in settings.Commands.Once ?? new List()) + { + if (command != null && command.Enabled && !string.IsNullOrWhiteSpace(command.CommandLine)) + { + RunCommand(command, "once"); + } + } + + StartContinuous(settings.Commands.Continuous); + } + + public void RunExitCommands(AppSettings settings) + { + StopContinuous(); + if (settings == null || settings.Commands == null) + { + return; + } + + RunSimple("退出", settings.Commands.OnExit); + } + + public void StartContinuous(IList commands) + { + StopContinuous(); + if (commands == null) + { + return; + } + + foreach (CommandDefinition command in commands) + { + if (command == null || !command.Enabled || string.IsNullOrWhiteSpace(command.CommandLine)) + { + continue; + } + + CommandDefinition captured = command; + int interval = Math.Max(1, command.IntervalSeconds) * 1000; + var timer = new System.Windows.Forms.Timer { Interval = Math.Min(interval, int.MaxValue - 1) }; + timer.Tick += delegate { RunCommandInBackground(captured, "on"); }; + lock (_sync) + { + _continuousTimers.Add(timer); + } + + timer.Start(); + AppLog.Info("持续命令已启动:" + captured + "(每 " + command.IntervalSeconds + " 秒)"); + } + } + + public void StopContinuous() + { + List timers; + lock (_sync) + { + timers = new List(_continuousTimers); + _continuousTimers.Clear(); + } + + foreach (System.Windows.Forms.Timer timer in timers) + { + timer.Stop(); + timer.Dispose(); + } + + if (timers.Count > 0) + { + AppLog.Info("持续命令已停止(" + timers.Count + " 条)。"); + } + } + + /// Runs one command and waits; used by the settings dialog's "立即执行" button. + public CommandResult RunCommand(CommandDefinition command, string trigger) + { + var result = new CommandResult + { + Name = command == null ? string.Empty : command.ToString() + }; + if (command == null || string.IsNullOrWhiteSpace(command.CommandLine)) + { + result.Error = "命令行为空。"; + return result; + } + + string key = command.CommandLine; + lock (_sync) + { + if (!_inFlight.Add(key)) + { + // A slow command must not pile up on top of itself. + result.Error = "上一次执行还没结束,已跳过这次。"; + return result; + } + } + + try + { + return Execute(command, trigger, result); + } + finally + { + lock (_sync) + { + _inFlight.Remove(key); + } + } + } + + private CommandResult Execute(CommandDefinition command, string trigger, CommandResult result) + { + var info = new ProcessStartInfo("cmd.exe", "/c " + command.CommandLine) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + WorkingDirectory = ResolveWorkingDirectory(command.WorkingDirectory) + }; + + var output = new StringBuilder(); + var errors = new StringBuilder(); + AppLog.Info("执行命令(" + trigger + "):" + command.CommandLine); + try + { + using (Process process = new Process { StartInfo = info }) + { + process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) + { + if (e.Data != null) + { + output.AppendLine(e.Data); + Raise(command.ToString(), e.Data, false); + } + }; + process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) + { + if (e.Data != null) + { + errors.AppendLine(e.Data); + Raise(command.ToString(), e.Data, true); + } + }; + + if (!process.Start()) + { + result.Error = "进程无法启动。"; + return result; + } + + result.Started = true; + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + int timeoutMs = Math.Max(1, command.TimeoutSeconds) * 1000; + if (!process.WaitForExit(timeoutMs)) + { + result.TimedOut = true; + TryKill(process); + AppLog.Warn("命令超时(" + command.TimeoutSeconds + " 秒),已结束:" + command.CommandLine); + } + else + { + process.WaitForExit(); // let the async readers flush + result.ExitCode = process.ExitCode; + } + } + } + catch (Exception ex) + { + result.Error = ex.GetType().Name + ": " + ex.Message; + AppLog.Error("命令执行失败:" + command.CommandLine, ex); + } + + result.Output = output.ToString(); + result.Error = result.Error ?? (errors.Length == 0 ? null : errors.ToString()); + AppLog.Info("命令结束(" + trigger + "):" + command + ";退出码=" + + (result.TimedOut ? "超时" : result.ExitCode.ToString())); + return result; + } + + private static void TryKill(Process process) + { + try + { + process.Kill(); + } + catch (Exception ex) + { + AppLog.Warn("结束超时命令失败:" + ex.GetType().Name); + } + } + + private static string ResolveWorkingDirectory(string configured) + { + if (!string.IsNullOrWhiteSpace(configured) && Directory.Exists(configured)) + { + return configured; + } + + string exeDirectory = Path.GetDirectoryName(typeof(CommandRunner).Assembly.Location); + return string.IsNullOrEmpty(exeDirectory) ? Directory.GetCurrentDirectory() : exeDirectory; + } + + private void RunSimple(string trigger, string commandLine) + { + if (string.IsNullOrWhiteSpace(commandLine)) + { + return; + } + + RunCommand( + new CommandDefinition { Name = trigger, CommandLine = commandLine, TimeoutSeconds = 30 }, + trigger); + } + + private void RunCommandInBackground(CommandDefinition command, string trigger) + { + // Continuous commands must not block the UI thread. + ThreadPool.QueueUserWorkItem(delegate { RunCommand(command, trigger); }); + } + + private void Raise(string name, string text, bool isError) + { + EventHandler handler = Output; + if (handler != null) + { + handler(this, new CommandOutputEventArgs(name, text, isError)); + } + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + StopContinuous(); + } + } +} diff --git a/src/pacs_win_uia/Services/ControlLocatorBuilder.cs b/src/pacs_win_uia/Services/ControlLocatorBuilder.cs new file mode 100644 index 0000000..67565e2 --- /dev/null +++ b/src/pacs_win_uia/Services/ControlLocatorBuilder.cs @@ -0,0 +1,402 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Automation; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Interop; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// What a control snapshot contributes to a monitor definition. + public sealed class ControlLocatorBuildResult + { + public ControlSourcePreference Source { get; set; } + + public string ProcessName { get; set; } + + public string WindowClass { get; set; } + + public string WindowTitleKeyword { get; set; } + + public List UiaPath { get; set; } + + public string MsaaPathKey { get; set; } + + public List Win32Path { get; set; } + + /// Human-readable path (display only). + public string DisplayPath { get; set; } + + public string RuntimeId { get; set; } + + public string ValueKey { get; set; } + + public string Value { get; set; } + + public bool IsComplete { get; set; } + + public string Note { get; set; } + } + + /// + /// 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 + /// how segments are produced and matched. + /// + public sealed class ControlLocatorBuilder + { + private const int MaxSiblingsToScan = 400; + + private readonly NativeWindowService _windowService; + + public ControlLocatorBuilder() + : this(new NativeWindowService()) + { + } + + public ControlLocatorBuilder(NativeWindowService windowService) + { + _windowService = windowService ?? throw new ArgumentNullException("windowService"); + } + + /// + /// Window fields always describe the TOP-LEVEL window: matching by a renderer child class + /// would never find the window again on the next run. + /// + public void ApplyWindowFields(ControlLocatorBuildResult result, NativeWindowInfo window) + { + if (result == null || window == null) + { + return; + } + + result.ProcessName = window.ProcessName; + NativeWindowInfo topLevel = window; + IntPtr root = NativeMethods.GetAncestor(window.Handle, NativeMethods.GA_ROOT); + if (root != IntPtr.Zero && root != window.Handle) + { + NativeWindowInfo captured = _windowService.Capture(root); + if (captured != null) + { + topLevel = captured; + } + } + + result.WindowClass = topLevel.ClassName; + result.WindowTitleKeyword = ShortenTitle(topLevel.Title); + if (string.IsNullOrEmpty(result.ProcessName)) + { + result.ProcessName = topLevel.ProcessName; + } + } + + public ControlLocatorBuildResult BuildFromUia(UiaElementInfo element, NativeWindowInfo window) + { + var result = new ControlLocatorBuildResult + { + Source = ControlSourcePreference.Uia, + UiaPath = new List(), + ValueKey = "Name" + }; + ApplyWindowFields(result, window); + if (element == null || element.Element == null) + { + result.Note = "没有可用的 UIA 元素。"; + return result; + } + + element.EnsureRuntimeId(); + result.RuntimeId = element.RuntimeId; + + IList segments; + string note; + // Record the path relative to the ROOT window: resolution starts at FromHandle(root HWND), + // so a path recorded relative to a nested window element (UWP CoreWindow, browser renderer) + // would never match. + IntPtr rootHandle = window == null + ? IntPtr.Zero + : NativeMethods.GetAncestor(window.Handle, NativeMethods.GA_ROOT); + bool complete = TryBuildUiaPath(element.Element, rootHandle, out segments, out note); + foreach (ControlLocatorSegment segment in segments) + { + result.UiaPath.Add(segment); + } + + result.ValueKey = "Name"; + result.Value = element.Name; + result.DisplayPath = ControlLocatorFormat.DescribeUiaPath(result.UiaPath); + result.IsComplete = complete && result.UiaPath.Count > 0; + if (result.UiaPath.Count == 0) + { + note = "拾取到的就是顶层窗口本身,没有可保存的下级路径;请在该窗口内部选取具体控件。"; + } + + result.Note = note; + return result; + } + + public ControlLocatorBuildResult BuildFromMsaa(MsaaNodeInfo node, NativeWindowInfo window) + { + var result = new ControlLocatorBuildResult + { + Source = ControlSourcePreference.Msaa, + ValueKey = string.IsNullOrEmpty(node == null ? null : node.Name) ? "accValue" : "accName" + }; + ApplyWindowFields(result, window); + if (node == null) + { + result.Note = "没有可用的 MSAA 节点。"; + return result; + } + + result.MsaaPathKey = ControlLocatorFormat.StripRoot(node.PathKey); + result.Value = string.Equals(result.ValueKey, "accName", StringComparison.Ordinal) ? node.Name : node.Value; + result.DisplayPath = result.MsaaPathKey; + result.IsComplete = !string.IsNullOrEmpty(result.MsaaPathKey); + result.Note = result.IsComplete ? null : "该 MSAA 节点就是窗口本身,没有可保存的下级路径。"; + return result; + } + + public ControlLocatorBuildResult BuildFromWin32(NativeWindowInfo target, NativeWindowInfo window) + { + var result = new ControlLocatorBuildResult + { + Source = ControlSourcePreference.Win32, + Win32Path = new List(), + ValueKey = "窗口标题" + }; + ApplyWindowFields(result, window); + if (target == null) + { + result.Note = "没有可用的 Win32 窗口。"; + return result; + } + + IntPtr rootHandle = NativeMethods.GetAncestor(target.Handle, NativeMethods.GA_ROOT); + IList segments = BuildWin32Path(rootHandle, target.Handle); + foreach (Win32LocatorSegment segment in segments) + { + result.Win32Path.Add(segment); + } + + result.Value = target.Title; + result.DisplayPath = ControlLocatorFormat.DescribeWin32Path(result.Win32Path); + result.IsComplete = result.Win32Path.Count > 0; + result.Note = result.IsComplete + ? null + : "选中的就是顶层窗口,没有可保存的下级窗口路径;请拾取窗口内部的子窗口。"; + return result; + } + + /// + /// Segments from the top-level window down to the element (the window itself is not a segment, + /// because resolution starts *at* the window). + /// + private static bool TryBuildUiaPath( + AutomationElement element, + IntPtr rootHandle, + out IList segments, + out string note) + { + var collected = new List(); + segments = collected; + note = null; + AutomationElement current = element; + for (int depth = 0; depth < 32 && current != null; depth++) + { + AutomationElement parent; + try + { + parent = TreeWalker.ControlViewWalker.GetParent(current); + } + catch (Exception ex) + { + note = "向上查找父元素失败:" + ex.GetType().Name + ": " + ex.Message; + return false; + } + + if (parent == null) + { + note = "没有找到顶层窗口(元素已脱离树)。"; + return false; + } + + AutomationElement.AutomationElementInformation parentInfo = parent.Current; + bool isRoot = rootHandle != IntPtr.Zero + ? new IntPtr(parentInfo.NativeWindowHandle) == rootHandle + : parentInfo.NativeWindowHandle != 0 && parentInfo.ControlType == ControlType.Window; + if (isRoot) + { + // `current` is a direct child of the root window, and the resolver starts AT the + // root — so this element is a path step. Dropping it shifted every saved path one + // level down and made resolution fail from the window. + collected.Add(BuildSegment(current, parent)); + break; + } + + if (parentInfo.NativeWindowHandle != 0 && parentInfo.ControlType == ControlType.Window && + rootHandle != IntPtr.Zero) + { + AppLog.Warn("构建 UIA 路径:经过了内层窗口元素 0x" + + parentInfo.NativeWindowHandle.ToString("X") + "(不是根窗口),路径仍会包含它。"); + } + + collected.Add(BuildSegment(current, parent)); + current = parent; + } + + collected.Reverse(); + return true; + } + + private static ControlLocatorSegment BuildSegment(AutomationElement element, AutomationElement parent) + { + AutomationElement.AutomationElementInformation info = element.Current; + var segment = new ControlLocatorSegment + { + ControlType = info.ControlType == null ? null : info.ControlType.ProgrammaticName, + Name = info.Name, + AutomationId = info.AutomationId, + Index = -1 + }; + segment.Index = SameTypeOrdinal(parent, element, segment.ControlType); + return segment; + } + + private static int SameTypeOrdinal(AutomationElement parent, AutomationElement target, string controlType) + { + try + { + AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(parent); + int ordinal = 0; + int scanned = 0; + while (child != null && scanned < MaxSiblingsToScan) + { + scanned++; + bool sameType = string.Equals( + child.Current.ControlType == null ? null : child.Current.ControlType.ProgrammaticName, + controlType, + StringComparison.Ordinal); + if (sameType) + { + if (child == target) + { + return ordinal; + } + + ordinal++; + } + + child = TreeWalker.ControlViewWalker.GetNextSibling(child); + } + } + catch (Exception ex) + { + AppLog.Warn("构建 UIA 路径时统计同级序号失败:" + ex.GetType().Name + ": " + ex.Message); + } + + return -1; + } + + /// Win32 path: each step is the class name plus its ordinal among same-class siblings. + public static IList BuildWin32Path(IntPtr rootHandle, IntPtr targetHandle) + { + var segments = new List(); + if (rootHandle == IntPtr.Zero || targetHandle == IntPtr.Zero || rootHandle == targetHandle) + { + return segments; + } + + var chain = new List(); + IntPtr current = targetHandle; + for (int depth = 0; depth < 32 && current != IntPtr.Zero && current != rootHandle; depth++) + { + chain.Add(current); + current = NativeMethods.GetAncestor(current, NativeMethods.GA_PARENT); + } + + if (current != rootHandle) + { + return segments; + } + + chain.Reverse(); + foreach (IntPtr handle in chain) + { + IntPtr parent = NativeMethods.GetAncestor(handle, NativeMethods.GA_PARENT); + segments.Add(new Win32LocatorSegment + { + ClassName = ReadClassName(handle), + Index = SameClassOrdinal(parent, handle) + }); + } + + return segments; + } + + private static int SameClassOrdinal(IntPtr parent, IntPtr target) + { + string targetClass = ReadClassName(target); + int ordinal = 0; + var children = new List(); + NativeMethods.EnumChildWindows( + parent, + delegate(IntPtr hWnd, IntPtr lParam) + { + IntPtr childParent = NativeMethods.GetAncestor(hWnd, NativeMethods.GA_PARENT); + if (childParent == parent) + { + children.Add(hWnd); + } + + return true; + }, + IntPtr.Zero); + + foreach (IntPtr child in children) + { + if (!string.Equals(ReadClassName(child), targetClass, StringComparison.Ordinal)) + { + continue; + } + + if (child == target) + { + return ordinal; + } + + ordinal++; + } + + return 0; + } + + private static string ReadClassName(IntPtr handle) + { + try + { + var builder = new StringBuilder(256); + NativeMethods.GetClassName(handle, builder, builder.Capacity); + return builder.ToString(); + } + catch (Exception ex) + { + AppLog.Warn("读取窗口类名失败:" + ex.GetType().Name); + return string.Empty; + } + } + + /// Titles change (file names, patient counts); a prefix is a stabler keyword. + private static string ShortenTitle(string title) + { + if (string.IsNullOrEmpty(title)) + { + return null; + } + + const int MaxKeywordLength = 24; + return title.Length <= MaxKeywordLength ? title : title.Substring(0, MaxKeywordLength); + } + } +} diff --git a/src/pacs_win_uia/Services/ControlLocatorService.cs b/src/pacs_win_uia/Services/ControlLocatorService.cs new file mode 100644 index 0000000..56bb739 --- /dev/null +++ b/src/pacs_win_uia/Services/ControlLocatorService.cs @@ -0,0 +1,917 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Windows.Automation; +using Accessibility; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Interop; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// Result of resolving one saved control. + public sealed class ControlResolution + { + public bool Found { get; set; } + + public ControlTreeSource ResolvedSource { get; set; } + + /// The resolved node; carries the per-source payload the value reader needs. + public ControlTreeNode Node { get; set; } + + public IntPtr WindowHandle { get; set; } + + public string Error { get; set; } + } + + /// + /// Re-resolves a saved control without any UI. Nothing here depends on a window existing: a saved + /// control is located through 进程名 + 窗口类名 + 标题关键词, then walked down its source-specific + /// path (UIA segments / MSAA child ids / Win32 class+ordinal). + /// + public sealed class ControlLocatorService + { + private const int MaxSiblingsToScan = 400; + + private readonly NativeWindowService _windowService; + private readonly UiAutomationService _uiAutomationService; + private readonly MsaaService _msaaService; + private readonly Win32TreeReader _win32TreeReader; + + public ControlLocatorService() + : this(new NativeWindowService(), new UiAutomationService(), new MsaaService(), new Win32TreeReader()) + { + } + + public ControlLocatorService( + NativeWindowService windowService, + UiAutomationService uiAutomationService, + MsaaService msaaService, + Win32TreeReader win32TreeReader) + { + _windowService = windowService ?? throw new ArgumentNullException("windowService"); + _uiAutomationService = uiAutomationService ?? throw new ArgumentNullException("uiAutomationService"); + _msaaService = msaaService ?? throw new ArgumentNullException("msaaService"); + _win32TreeReader = win32TreeReader ?? throw new ArgumentNullException("win32TreeReader"); + } + + // ------------------------------------------------------------------ top-level window + + /// + /// 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. + /// + public IntPtr FindTargetWindow(ControlMonitorDefinition definition, IList steps, out string error) + { + error = null; + if (definition == null) + { + error = "定义为空。"; + return IntPtr.Zero; + } + + if (string.IsNullOrEmpty(definition.ProcessName) && string.IsNullOrEmpty(definition.WindowClass) && + string.IsNullOrEmpty(definition.WindowTitleKeyword)) + { + error = "没有保存窗口定位信息(进程名/窗口类名/标题关键词),无法在无界面模式下找到目标窗口。" + + "请在界面上重新「添加当前控件」。"; + return IntPtr.Zero; + } + + IList windows = _windowService.EnumerateTopLevelWindows(false); + IntPtr best = IntPtr.Zero; + int bestLevel = 0; + NativeWindowInfo bestWindow = null; + int bestCount = 0; + + // Most precise first. The saved window class can change when the target application is + // updated (WinForms class names embed a build hash) and the title keyword can follow the + // data it shows, so a narrower match must not fail the whole lookup. + for (int level = MatchingLevels; level >= 1 && best == IntPtr.Zero; level--) + { + var candidates = new List(); + foreach (NativeWindowInfo window in windows) + { + if (MatchesWindow(window, definition, level)) + { + candidates.Add(window); + } + } + + if (candidates.Count == 0) + { + continue; + } + + best = candidates[0].Handle; + bestWindow = candidates[0]; + bestLevel = level; + bestCount = candidates.Count; + } + + if (best == IntPtr.Zero) + { + error = string.Format( + "没有匹配的顶层窗口(进程名=\"{0}\";窗口类名=\"{1}\";标题关键词=\"{2}\");当前可见顶层窗口 {3} 个。", + definition.ProcessName, definition.WindowClass, definition.WindowTitleKeyword, windows.Count); + return IntPtr.Zero; + } + + string levelText = DescribeMatchLevel(bestLevel); + steps.Add(string.Format("匹配到顶层窗口 0x{0:X}({1} / {2},匹配级别:{3}){4}", + bestWindow.Handle.ToInt64(), bestWindow.ProcessName, bestWindow.ClassName, levelText, + bestCount > 1 ? ";还有 " + (bestCount - 1) + " 个候选,已取 z 序最前的一个" : string.Empty)); + if (bestLevel <= 2) + { + steps.Add("注意:这次不是按“进程名+窗口类名+标题关键词”完全匹配的——目标程序可能升级过" + + "(窗口类名会变)或标题随内容变化了。建议在界面里重新添加一次该控件。"); + } + + return best; + } + + private const int MatchingLevels = 4; + + /// + /// 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 + /// than title text. + /// + private static bool MatchesWindow(NativeWindowInfo window, ControlMonitorDefinition definition, int level) + { + bool hasProcess = !string.IsNullOrEmpty(definition.ProcessName); + bool sameProcess = hasProcess && + string.Equals(window.ProcessName, definition.ProcessName, StringComparison.OrdinalIgnoreCase); + if (hasProcess && !sameProcess) + { + return false; + } + + bool sameClass = !string.IsNullOrEmpty(definition.WindowClass) && + string.Equals(window.ClassName, definition.WindowClass, StringComparison.Ordinal); + bool sameTitle = !string.IsNullOrEmpty(definition.WindowTitleKeyword) && + window.Title != null && + window.Title.IndexOf(definition.WindowTitleKeyword, StringComparison.OrdinalIgnoreCase) >= 0; + + switch (level) + { + case 4: + return sameProcess && sameClass && sameTitle; + case 3: + return sameProcess && sameClass; + case 2: + return sameProcess && sameTitle; + default: + // Without a process name this would match every window, so require at least one + // of class/title or refuse. + if (!hasProcess) + { + return sameClass || sameTitle; + } + + return sameProcess; + } + } + + private static string DescribeMatchLevel(int level) + { + switch (level) + { + case 4: + return "进程名+窗口类名+标题关键词"; + case 3: + return "进程名+窗口类名(标题关键词没匹配上)"; + case 2: + return "进程名+标题关键词(窗口类名没匹配上)"; + default: + return "只有进程名(较宽)"; + } + } + + // ------------------------------------------------------------------ control resolution + + /// Resolves the control with the preferred source, falling back to the other two. + public ControlResolution Resolve(ControlMonitorDefinition definition, IntPtr windowHandle, IList steps) + { + var order = SourceOrder(definition.Source); + string preferredError = null; + foreach (ControlTreeSource source in order) + { + ControlResolution resolution = TryResolveBySource(definition, windowHandle, source, steps); + if (resolution.Found) + { + // The preferred source may legitimately resolve to the window itself (empty path). + // A *fallback* doing that only proves the window exists, not that the requested + // control was found — reporting success there would be misleading. + if (preferredError == null || HasSavedPath(definition, source)) + { + if (preferredError != null) + { + steps.Add(source + " 回退定位成功(该来源保存了完整路径)。"); + } + + return resolution; + } + + steps.Add(source + " 回退只定位到顶层窗口本身(该来源没有保存下级路径),不算命中。"); + if (preferredError == null) + { + preferredError = resolution.Error; + } + + continue; + } + + // The preferred source's reason is the meaningful one; the fallbacks mostly report + // "this source has no saved path". + if (preferredError == null) + { + preferredError = resolution.Error; + } + + if (order.Count > 1) + { + steps.Add(source + " 定位失败:" + (resolution.Error ?? "未知原因")); + } + } + + return new ControlResolution + { + Found = false, + WindowHandle = windowHandle, + Error = preferredError ?? "该控件在所有来源下都没有定位到。" + }; + } + + /// True when the definition actually saved a path for that source. + private static bool HasSavedPath(ControlMonitorDefinition definition, ControlTreeSource source) + { + switch (source) + { + case ControlTreeSource.Msaa: + return !string.IsNullOrEmpty(definition.MsaaPathKey); + case ControlTreeSource.Win32: + return definition.Win32Path != null && definition.Win32Path.Count > 0; + default: + return definition.UiaPath != null && definition.UiaPath.Count > 0; + } + } + + private static List SourceOrder(ControlSourcePreference preference) + { + var order = new List(); + switch (preference) + { + case ControlSourcePreference.Uia: + order.Add(ControlTreeSource.Uia); + break; + case ControlSourcePreference.Msaa: + order.Add(ControlTreeSource.Msaa); + break; + case ControlSourcePreference.Win32: + order.Add(ControlTreeSource.Win32); + break; + default: + order.Add(ControlTreeSource.Uia); + order.Add(ControlTreeSource.Msaa); + order.Add(ControlTreeSource.Win32); + return order; + } + + // Preferred source first, then the fallbacks, so a config keeps working when only one + // source is unavailable. + foreach (ControlTreeSource candidate in new[] + { + ControlTreeSource.Uia, ControlTreeSource.Msaa, ControlTreeSource.Win32 + }) + { + if (candidate != order[0]) + { + order.Add(candidate); + } + } + + return order; + } + + private ControlResolution TryResolveBySource( + ControlMonitorDefinition definition, + IntPtr windowHandle, + ControlTreeSource source, + IList steps) + { + switch (source) + { + case ControlTreeSource.Msaa: + return ResolveMsaa(definition, windowHandle, steps); + case ControlTreeSource.Win32: + return ResolveWin32(definition, windowHandle, steps); + default: + return ResolveUia(definition, windowHandle, steps); + } + } + + private ControlResolution ResolveUia(ControlMonitorDefinition definition, IntPtr windowHandle, IList steps) + { + if (definition.UiaPath == null || definition.UiaPath.Count == 0) + { + return ResolveWindowItselfUia(windowHandle, steps); + } + + AutomationElement root; + try + { + root = AutomationElement.FromHandle(windowHandle); + } + catch (Exception ex) + { + return new ControlResolution { Error = "无法从 HWND 取得 UIA 根元素:" + ex.Message }; + } + + if (root == null) + { + return new ControlResolution { Error = "AutomationElement.FromHandle 返回空。" }; + } + + // First try the saved path starting at the window itself. + string reason; + AutomationElement match = WalkPath(root, definition.UiaPath, out reason); + if (match != null) + { + UiaElementInfo direct = _uiAutomationService.Inspect(match); + steps.Add("UIA 路径 " + definition.UiaPath.Count + " 段全部匹配(从顶层窗口开始),命中 " + direct); + return new ControlResolution + { + Found = true, + ResolvedSource = ControlTreeSource.Uia, + WindowHandle = windowHandle, + Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = direct } + }; + } + + string firstFailure = reason; + + // Some hosts (UWP ApplicationFrameWindow, browser shells) own an inner window element and + // the tree was read from that element, so a saved path can be relative to it. + foreach (AutomationElement start in CollectNestedWindowStarts(root, windowHandle)) + { + string nestedReason; + AutomationElement nestedMatch = WalkPath(start, definition.UiaPath, out nestedReason); + if (nestedMatch == null) + { + continue; + } + + UiaElementInfo info = _uiAutomationService.Inspect(nestedMatch); + steps.Add("从顶层窗口开始匹配失败(" + firstFailure + "),改从内层窗口元素 " + + NativeWindowInfo.FormatHandle((IntPtr)SafeNativeHandle(start)) + " 开始匹配成功。"); + return new ControlResolution + { + Found = true, + ResolvedSource = ControlTreeSource.Uia, + WindowHandle = windowHandle, + Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = info } + }; + } + + // Last resort: the control tree gained or lost a level (XAML/Chromium trees change between + // versions and page states). Drop up to two leading segments and accept the result only + // when exactly ONE element in the window matches the remaining path. + for (int skip = 1; skip <= MaxSkippedPrefixSegments && skip < definition.UiaPath.Count; skip++) + { + var remaining = new List(); + for (int index = skip; index < definition.UiaPath.Count; index++) + { + remaining.Add(definition.UiaPath[index]); + } + + List candidates = FindSegments(root, remaining[0]); + if (candidates.Count == 0) + { + continue; + } + + var matches = new List(); + foreach (AutomationElement candidate in candidates) + { + var tail = new List(); + for (int index = 1; index < remaining.Count; index++) + { + tail.Add(remaining[index]); + } + + string tailReason; + AutomationElement tailMatch = tail.Count == 0 ? candidate : WalkPath(candidate, tail, out tailReason); + if (tailMatch != null && !matches.Contains(tailMatch)) + { + matches.Add(tailMatch); + } + } + + if (matches.Count != 1) + { + steps.Add(string.Format( + "跳过前 {0} 段后在窗口内找到 {1} 个候选(要求唯一才算命中),放弃该方案。", + skip, matches.Count)); + continue; + } + + UiaElementInfo flexible = _uiAutomationService.Inspect(matches[0]); + steps.Add(string.Format( + "完整路径未命中,但跳过前 {0} 段后在整个窗口内**唯一**匹配到 {1}。" + + "说明控件树层级与保存时不同(程序版本或页面状态变了),建议在界面里重新添加该控件。", + skip, flexible)); + return new ControlResolution + { + Found = true, + ResolvedSource = ControlTreeSource.Uia, + WindowHandle = windowHandle, + Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = flexible } + }; + } + + return new ControlResolution + { + Error = string.Format("UIA 路径第 1 段起点匹配失败:{0}", firstFailure) + }; + } + + /// Walks a saved UIA path from a start element; returns null with a reason on failure. + private static AutomationElement WalkPath( + AutomationElement start, + IList path, + out string failureReason) + { + failureReason = null; + AutomationElement current = start; + for (int index = 0; index < path.Count; index++) + { + ControlLocatorSegment segment = path[index]; + AutomationElement next; + string reason; + if (!TryMatchChild(current, segment, out next, out reason)) + { + failureReason = string.Format("第 {0} 段({1})未匹配:{2}", index + 1, segment, reason); + return null; + } + + current = next; + } + + return current; + } + + private const int MaxSkippedPrefixSegments = 2; + private const int SegmentSearchDepth = 10; + private const int SegmentSearchNodes = 1500; + private const int MaxSegmentCandidates = 20; + + /// + /// Every element in the window's subtree matching one segment, by AutomationId first (exact) + /// and otherwise by ControlType + Name. Bounded; the ordinal is meaningless in a subtree-wide + /// search, so it is not used here. + /// + private static List FindSegments(AutomationElement root, ControlLocatorSegment segment) + { + var found = new List(); + if (segment == null || (string.IsNullOrEmpty(segment.AutomationId) && string.IsNullOrEmpty(segment.Name))) + { + return found; + } + + try + { + var queue = new Queue>(); + queue.Enqueue(new KeyValuePair(root, 0)); + int visited = 0; + while (queue.Count > 0 && visited < SegmentSearchNodes && found.Count < MaxSegmentCandidates) + { + KeyValuePair item = queue.Dequeue(); + visited++; + if (item.Value >= SegmentSearchDepth) + { + continue; + } + + AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(item.Key); + int scanned = 0; + while (child != null && scanned < MaxSiblingsToScan) + { + scanned++; + try + { + AutomationElement.AutomationElementInformation info = child.Current; + string controlType = info.ControlType == null ? null : info.ControlType.ProgrammaticName; + bool matches = !string.IsNullOrEmpty(segment.AutomationId) + ? string.Equals(info.AutomationId, segment.AutomationId, StringComparison.Ordinal) + : string.Equals(controlType, segment.ControlType, StringComparison.Ordinal) && + string.Equals(info.Name, segment.Name, StringComparison.Ordinal); + if (matches && found.Count < MaxSegmentCandidates) + { + found.Add(child); + } + } + catch (Exception) + { + // Skip an unreadable element; the search continues. + } + + queue.Enqueue(new KeyValuePair(child, item.Value + 1)); + child = TreeWalker.ControlViewWalker.GetNextSibling(child); + } + } + } + catch (Exception ex) + { + AppLog.Warn("在窗口内搜索定位段失败:" + ex.GetType().Name + ": " + ex.Message); + } + + return found; + } + + private const int NestedWindowScanDepth = 4; + private const int NestedWindowScanNodes = 200; + private const int MaxNestedWindowStarts = 4; + + /// + /// Nested window-typed elements with their own HWND, breadth-first and bounded. A UWP app's + /// CoreWindow and a browser's renderer window both qualify. + /// + private static IList CollectNestedWindowStarts(AutomationElement root, IntPtr rootHandle) + { + var starts = new List(); + try + { + var queue = new Queue>(); + queue.Enqueue(new KeyValuePair(root, 0)); + int visited = 0; + while (queue.Count > 0 && visited < NestedWindowScanNodes && starts.Count < MaxNestedWindowStarts) + { + KeyValuePair item = queue.Dequeue(); + visited++; + if (item.Value >= NestedWindowScanDepth) + { + continue; + } + + AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(item.Key); + int scanned = 0; + while (child != null && scanned < MaxSiblingsToScan) + { + scanned++; + try + { + AutomationElement.AutomationElementInformation info = child.Current; + if (info.ControlType == ControlType.Window && + info.NativeWindowHandle != 0 && + new IntPtr(info.NativeWindowHandle) != rootHandle && + starts.Count < MaxNestedWindowStarts) + { + starts.Add(child); + } + } + catch (Exception) + { + // A provider that refuses one child must not abort the scan. + } + + queue.Enqueue(new KeyValuePair(child, item.Value + 1)); + child = TreeWalker.ControlViewWalker.GetNextSibling(child); + } + } + } + catch (Exception ex) + { + AppLog.Warn("收集内层窗口元素失败:" + ex.GetType().Name + ": " + ex.Message); + } + + return starts; + } + + private static long SafeNativeHandle(AutomationElement element) + { + try + { + return element.Current.NativeWindowHandle; + } + catch (Exception) + { + return 0; + } + } + + /// AutomationId first, then type+name, then ordinal — the same order the builder records. + private static bool TryMatchChild(AutomationElement parent, ControlLocatorSegment segment, out AutomationElement match, out string reason) + { + match = null; + reason = null; + var sameType = new List(); + try + { + AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(parent); + int scanned = 0; + while (child != null && scanned < MaxSiblingsToScan) + { + scanned++; + AutomationElement.AutomationElementInformation info = child.Current; + string controlType = info.ControlType == null ? null : info.ControlType.ProgrammaticName; + bool sameControlType = string.Equals(controlType, segment.ControlType, StringComparison.Ordinal); + if (sameControlType) + { + sameType.Add(child); + } + + if (!string.IsNullOrEmpty(segment.AutomationId) && + string.Equals(info.AutomationId, segment.AutomationId, StringComparison.Ordinal)) + { + match = child; + return true; + } + + if (sameControlType && !string.IsNullOrEmpty(segment.Name) && + string.Equals(info.Name, segment.Name, StringComparison.Ordinal)) + { + match = child; + return true; + } + + child = TreeWalker.ControlViewWalker.GetNextSibling(child); + } + + if (scanned >= MaxSiblingsToScan) + { + reason = "同级子元素超过 " + MaxSiblingsToScan + " 个,扫描被截断"; + } + } + catch (Exception ex) + { + reason = "枚举子元素失败:" + ex.GetType().Name + ": " + ex.Message; + return false; + } + + if (segment.Index >= 0 && segment.Index < sameType.Count) + { + match = sameType[segment.Index]; + return true; + } + + reason = reason ?? string.Format("没有匹配的同级元素(同类元素 {0} 个,期望序号 {1})", sameType.Count, segment.Index); + return false; + } + + /// + /// An empty path is not an error: it means "the top-level window itself", which is a valid + /// thing to monitor (its title, class, visibility...). + /// + private ControlResolution ResolveWindowItselfUia(IntPtr windowHandle, IList steps) + { + try + { + UiaElementInfo info = _uiAutomationService.FromHandle(windowHandle); + steps.Add("没有保存 UIA 下级路径,定位到顶层窗口本身。"); + return new ControlResolution + { + Found = true, + ResolvedSource = ControlTreeSource.Uia, + WindowHandle = windowHandle, + Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = info } + }; + } + catch (Exception ex) + { + return new ControlResolution { Error = "读取顶层窗口的 UIA 元素失败:" + ex.Message }; + } + } + + private ControlResolution ResolveWindowItselfMsaa(IntPtr windowHandle, IList steps) + { + object accessibleObject; + string error; + if (!_msaaService.TryGetRoot(windowHandle, out accessibleObject, out error)) + { + return new ControlResolution { Error = "无法取得 MSAA 根对象:" + error }; + } + + var accessible = accessibleObject as IAccessible; + if (accessible == null) + { + return new ControlResolution { Error = "MSAA 根对象不是 IAccessible。" }; + } + + try + { + MsaaNodeInfo info = _msaaService.ReadSelf(accessible, MsaaNativeMethods.CHILDID_SELF, + "0x" + windowHandle.ToInt64().ToString("X")); + steps.Add("没有保存 MSAA 下级路径,定位到顶层窗口本身。"); + return new ControlResolution + { + Found = true, + ResolvedSource = ControlTreeSource.Msaa, + WindowHandle = windowHandle, + Node = new ControlTreeNode { Source = ControlTreeSource.Msaa, Msaa = info } + }; + } + finally + { + try + { + Marshal.ReleaseComObject(accessible); + } + catch (Exception) + { + // Best effort. + } + } + } + + private ControlResolution ResolveWindowItselfWin32(IntPtr windowHandle, IList steps) + { + ControlTreeNode root = _win32TreeReader.Read(windowHandle, new ControlTreeOptions(), System.Threading.CancellationToken.None); + if (root == null || root.Window == null) + { + return new ControlResolution { Error = "读取顶层窗口信息失败。" }; + } + + steps.Add("没有保存 Win32 下级路径,定位到顶层窗口本身。"); + return new ControlResolution + { + Found = true, + ResolvedSource = ControlTreeSource.Win32, + WindowHandle = windowHandle, + Node = root + }; + } + + private ControlResolution ResolveMsaa(ControlMonitorDefinition definition, IntPtr windowHandle, IList steps) + { + IList parts = ControlLocatorFormat.SplitMsaaPath(definition.MsaaPathKey); + if (parts.Count == 0) + { + return ResolveWindowItselfMsaa(windowHandle, steps); + } + + object accessibleObject; + string error; + if (!_msaaService.TryGetRoot(windowHandle, out accessibleObject, out error)) + { + return new ControlResolution { Error = "无法取得 MSAA 根对象:" + error }; + } + + var accessible = accessibleObject as IAccessible; + if (accessible == null) + { + return new ControlResolution { Error = "MSAA 根对象不是 IAccessible。" }; + } + + try + { + IAccessible current = accessible; + object currentChildId = MsaaNativeMethods.CHILDID_SELF; + List owned = new List(); + try + { + for (int index = 0; index < parts.Count; index++) + { + string part = parts[index]; + if (part.Length < 2) + { + return new ControlResolution { Error = "MSAA 路径第 " + (index + 1) + " 段格式不正确:" + part }; + } + + int ordinal; + if (!int.TryParse(part.Substring(1), out ordinal)) + { + return new ControlResolution { Error = "MSAA 路径第 " + (index + 1) + " 段不是数字:" + part }; + } + + if (part[0] == 'i') + { + // A simple child id: still read through the same parent object. + currentChildId = ordinal; + continue; + } + + bool complete; + string childError; + IList children = _msaaService.ReadChildren( + current, currentChildId, "walk", ordinal + 1, out complete, out childError); + if (ordinal >= children.Count) + { + return new ControlResolution + { + Error = string.Format("MSAA 路径第 {0} 段({1})越界:该层只有 {2} 个子元素({3})", + index + 1, part, children.Count, childError ?? "无错误信息") + }; + } + + MsaaChild child = children[ordinal]; + if (!child.IsObject || child.Accessible == null) + { + // A simple id in an object slot still resolves through the parent. + currentChildId = child.ChildId; + continue; + } + + owned.Add(child); + current = child.Accessible; + currentChildId = MsaaNativeMethods.CHILDID_SELF; + } + + MsaaNodeInfo node = _msaaService.ReadSelf(current, currentChildId, "0x" + windowHandle.ToInt64().ToString("X")); + steps.Add("MSAA 路径 " + parts.Count + " 段全部匹配,命中 " + node); + return new ControlResolution + { + Found = true, + ResolvedSource = ControlTreeSource.Msaa, + WindowHandle = windowHandle, + Node = new ControlTreeNode { Source = ControlTreeSource.Msaa, Msaa = node } + }; + } + finally + { + foreach (MsaaChild child in owned) + { + child.Release(); + } + } + } + finally + { + try + { + Marshal.ReleaseComObject(accessible); + } + catch (Exception) + { + // Best effort. + } + } + } + + private ControlResolution ResolveWin32(ControlMonitorDefinition definition, IntPtr windowHandle, IList steps) + { + if (definition.Win32Path == null || definition.Win32Path.Count == 0) + { + return ResolveWindowItselfWin32(windowHandle, steps); + } + + ControlTreeNode root = _win32TreeReader.Read(windowHandle, new ControlTreeOptions(), System.Threading.CancellationToken.None); + ControlTreeNode current = root; + for (int index = 0; index < definition.Win32Path.Count; index++) + { + Win32LocatorSegment segment = definition.Win32Path[index]; + ControlTreeNode next = MatchWindowChild(current, segment); + if (next == null) + { + return new ControlResolution + { + Error = string.Format("Win32 路径第 {0} 段({1})未匹配:该层没有对应类名与序号的子窗口(同级 {2} 个)", + index + 1, segment, current == null ? 0 : current.Children.Count) + }; + } + + current = next; + } + + steps.Add("Win32 路径 " + definition.Win32Path.Count + " 段全部匹配,命中 " + (current == null ? "(空)" : current.Describe())); + return new ControlResolution + { + Found = true, + ResolvedSource = ControlTreeSource.Win32, + WindowHandle = current != null && current.Window != null ? current.Window.Handle : windowHandle, + Node = current + }; + } + + private static ControlTreeNode MatchWindowChild(ControlTreeNode parent, Win32LocatorSegment segment) + { + if (parent == null) + { + return null; + } + + int ordinal = 0; + foreach (ControlTreeNode child in parent.Children) + { + if (child.Window == null) + { + continue; + } + + if (!string.Equals(child.Window.ClassName, segment.ClassName, StringComparison.Ordinal)) + { + continue; + } + + if (ordinal == segment.Index) + { + return child; + } + + ordinal++; + } + + return null; + } + } +} diff --git a/src/pacs_win_uia/Services/ControlMonitorStore.cs b/src/pacs_win_uia/Services/ControlMonitorStore.cs new file mode 100644 index 0000000..f99cc0b --- /dev/null +++ b/src/pacs_win_uia/Services/ControlMonitorStore.cs @@ -0,0 +1,310 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Xml; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// Persists monitor definitions only. Saving is an explicit caller action. + /// + public sealed class ControlMonitorStore + { + private const int CurrentVersion = 1; + private const int MaxDefinitions = ControlMonitorRules.MaxDefinitions; + private const int MaxFileBytes = ControlMonitorRules.MaxDocumentBytes; + private readonly string _filePath; + + public ControlMonitorStore() + : this(GetDefaultFilePath()) + { + } + + public ControlMonitorStore(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentException("A control monitor file path is required.", "filePath"); + } + + _filePath = Path.GetFullPath(filePath); + } + + public string FilePath + { + get { return _filePath; } + } + + public IList Load() + { + FileStream stream; + try + { + stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); + } + catch (FileNotFoundException) + { + return new List(); + } + catch (DirectoryNotFoundException) + { + return new List(); + } + + using (stream) + { + if (stream.Length > MaxFileBytes) + { + throw new InvalidDataException("The control monitor file exceeds the 1 MB limit."); + } + + StoreDocument document; + try + { + var quotas = new XmlDictionaryReaderQuotas + { + MaxDepth = 16, + MaxStringContentLength = MaxFileBytes, + MaxArrayLength = MaxDefinitions, + MaxBytesPerRead = 4096, + MaxNameTableCharCount = 16384 + }; + using (XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(stream, quotas)) + { + document = (StoreDocument)CreateSerializer().ReadObject(reader); + if (reader.MoveToContent() != XmlNodeType.None) + { + throw new InvalidDataException("The control monitor file has trailing JSON content."); + } + } + } + catch (SerializationException exception) + { + throw new InvalidDataException("The control monitor file is not a valid definition document.", exception); + } + catch (XmlException exception) + { + throw new InvalidDataException("The control monitor file contains invalid JSON.", exception); + } + + if (document == null) + { + throw new InvalidDataException("The control monitor document must not be null."); + } + if (document.Version != CurrentVersion) + { + throw new InvalidDataException("Unsupported control monitor document version; expected version 1."); + } + + IList errors = ControlMonitorRules.ValidateList(document.Items); + if (errors.Count > 0) + { + throw new InvalidDataException("控件监控定义文件内容无效:" + DescribeErrors(errors)); + } + + return document.Items; + } + } + + public void Save(IEnumerable definitions) + { + if (definitions == null) + { + throw new ArgumentNullException("definitions"); + } + + // Copy mutable definitions before validation and serialization. + var items = new List(); + foreach (ControlMonitorDefinition definition in definitions) + { + if (items.Count >= MaxDefinitions) + { + throw new InvalidDataException("At most 500 control monitor definitions are allowed."); + } + items.Add(definition == null ? null : CopyDefinition(definition)); + } + + IList errors = ControlMonitorRules.ValidateList(items); + if (errors.Count > 0) + { + throw new InvalidDataException("控件监控定义无效:" + DescribeErrors(errors)); + } + + byte[] data; + using (var stream = new MemoryStream()) + { + CreateSerializer().WriteObject(stream, new StoreDocument + { + Version = CurrentVersion, + Items = items + }); + if (stream.Length > MaxFileBytes) + { + throw new InvalidDataException("The control monitor document exceeds the 1 MB limit."); + } + data = stream.ToArray(); + } + + string directory = Path.GetDirectoryName(FilePath); + Directory.CreateDirectory(directory); + string temporaryPath = Path.Combine(directory, ".control-monitors-" + Guid.NewGuid().ToString("N") + ".tmp"); + bool ownsTemporaryFile = false; + try + { + using (var stream = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + ownsTemporaryFile = true; + stream.Write(data, 0, data.Length); + stream.Flush(true); + } + + if (File.Exists(FilePath)) + { + File.Replace(temporaryPath, FilePath, null); + } + else + { + File.Move(temporaryPath, FilePath); + } + ownsTemporaryFile = false; + } + catch (Exception saveException) + { + if (ownsTemporaryFile) + { + try + { + File.Delete(temporaryPath); + } + catch (Exception cleanupException) + { + throw new AggregateException( + "Saving control monitor definitions failed, and the temporary file could not be removed: " + temporaryPath, + saveException, cleanupException); + } + } + throw; + } + } + + private static string GetDefaultFilePath() + { + string directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (string.IsNullOrWhiteSpace(directory)) + { + throw new InvalidOperationException("The local application data directory is unavailable."); + } + return Path.Combine(directory, "pacs_win_uia", "control-monitors.json"); + } + + private static DataContractJsonSerializer CreateSerializer() + { + return new DataContractJsonSerializer(typeof(StoreDocument)); + } + + /// + /// 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. + /// + private static ControlMonitorDefinition CopyDefinition(ControlMonitorDefinition definition) + { + var copy = new ControlMonitorDefinition + { + Id = definition.Id, + ControlPath = definition.ControlPath, + PageFeatures = definition.PageFeatures, + ContentKey = definition.ContentKey, + RuntimeId = definition.RuntimeId, + Source = definition.Source, + ProcessName = definition.ProcessName, + WindowClass = definition.WindowClass, + WindowTitleKeyword = definition.WindowTitleKeyword, + MsaaPathKey = definition.MsaaPathKey, + ValueKey = definition.ValueKey, + Value = definition.Value, + Disabled = definition.Disabled, + TimeoutSeconds = definition.TimeoutSeconds + }; + + if (definition.UiaPath != null) + { + foreach (ControlLocatorSegment segment in definition.UiaPath) + { + if (segment != null) + { + copy.UiaPath.Add(new ControlLocatorSegment + { + ControlType = segment.ControlType, + Name = segment.Name, + AutomationId = segment.AutomationId, + Index = segment.Index + }); + } + } + } + + if (definition.Win32Path != null) + { + foreach (Win32LocatorSegment segment in definition.Win32Path) + { + if (segment != null) + { + copy.Win32Path.Add(new Win32LocatorSegment + { + ClassName = segment.ClassName, + Index = segment.Index + }); + } + } + } + + return copy; + } + + /// + /// Exposes the same rules the store enforces so the editor can show every problem at once + /// instead of relying on a thrown exception. + /// + public static IList TryValidate(IList definitions) + { + return ControlMonitorRules.ValidateList(definitions); + } + + private static string DescribeErrors(IList errors) + { + const int MaxReported = 5; + var builder = new StringBuilder(); + for (int index = 0; index < errors.Count; index++) + { + if (index == MaxReported) + { + builder.Append(" 等共 ").Append(errors.Count).Append(" 处问题。"); + break; + } + + if (index > 0) + { + builder.Append(";"); + } + + builder.Append(errors[index]); + } + + return builder.ToString(); + } + + [DataContract] + private sealed class StoreDocument + { + [DataMember(Order = 1, IsRequired = true)] + public int Version { get; set; } + + [DataMember(Order = 2, IsRequired = true)] + public List Items { get; set; } + } + } +} diff --git a/src/pacs_win_uia/Services/ControlTreeExporter.cs b/src/pacs_win_uia/Services/ControlTreeExporter.cs new file mode 100644 index 0000000..652ab99 --- /dev/null +++ b/src/pacs_win_uia/Services/ControlTreeExporter.cs @@ -0,0 +1,134 @@ +using System; +using System.IO; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +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. + /// + [DataContract] + public sealed class ControlTreeDocument + { + [DataMember(Order = 1)] + public DateTime ExportedAtUtc { get; set; } + + /// Null when auto mode was used. + [DataMember(Order = 2, EmitDefaultValue = false)] + public ControlTreeSource? RequestedSource { get; set; } + + [DataMember(Order = 3)] + public bool UiaAvailable { get; set; } + + [DataMember(Order = 4)] + public bool MsaaAvailable { get; set; } + + [DataMember(Order = 5)] + public bool Win32Available { get; set; } + + [DataMember(Order = 6)] + public ControlTreeNode Root { get; set; } + } + + /// + /// Exports only snapshot DTOs. Live HWND, AutomationElement and IAccessible instances are never + /// serialized. + /// + public sealed class ControlTreeExporter + { + public void Export(ControlTreeNode tree, ControlTreeSource? source, string filePath) + { + if (tree == null) + { + throw new ArgumentNullException("tree"); + } + + WriteObject(new ControlTreeDocument + { + ExportedAtUtc = DateTime.UtcNow, + RequestedSource = source, + UiaAvailable = ContainsSource(tree, ControlTreeSource.Uia), + MsaaAvailable = ContainsSource(tree, ControlTreeSource.Msaa), + Win32Available = ContainsSource(tree, ControlTreeSource.Win32), + Root = tree + }, filePath); + } + + public string Serialize(ControlTreeNode tree, ControlTreeSource? source) + { + if (tree == null) + { + throw new ArgumentNullException("tree"); + } + + var document = new ControlTreeDocument + { + ExportedAtUtc = DateTime.UtcNow, + RequestedSource = source, + UiaAvailable = ContainsSource(tree, ControlTreeSource.Uia), + MsaaAvailable = ContainsSource(tree, ControlTreeSource.Msaa), + Win32Available = ContainsSource(tree, ControlTreeSource.Win32), + Root = tree + }; + + return Serialize(document); + } + + private static bool ContainsSource(ControlTreeNode node, ControlTreeSource source) + { + if (node == null) + { + return false; + } + + if (node.Source == source) + { + return true; + } + + foreach (ControlTreeNode child in node.Children) + { + if (ContainsSource(child, source)) + { + return true; + } + } + + return false; + } + + private static void WriteObject(object value, string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentException("导出路径不能为空。", "filePath"); + } + + string fullPath = Path.GetFullPath(filePath); + string directory = Path.GetDirectoryName(fullPath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + var serializer = new DataContractJsonSerializer(value.GetType()); + using (var stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + serializer.WriteObject(stream, value); + } + } + + private static string Serialize(object value) + { + var serializer = new DataContractJsonSerializer(value.GetType()); + using (var stream = new MemoryStream()) + { + serializer.WriteObject(stream, value); + return System.Text.Encoding.UTF8.GetString(stream.ToArray()); + } + } + } +} diff --git a/src/pacs_win_uia/Services/ControlTreeService.cs b/src/pacs_win_uia/Services/ControlTreeService.cs new file mode 100644 index 0000000..c456395 --- /dev/null +++ b/src/pacs_win_uia/Services/ControlTreeService.cs @@ -0,0 +1,359 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using System.Windows.Automation; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + public sealed class ControlTreeResult + { + 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; } + } + + /// + /// 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 + /// it is a local enumeration that cannot hang. + /// + public sealed class ControlTreeService + { + /// How long to wait for an asynchronously built content tree before re-reading. + private const int ChromeContentRetryDelayMs = 700; + + private readonly UiAutomationService _uiAutomationService; + private readonly MsaaTreeReader _msaaTreeReader; + private readonly Win32TreeReader _win32TreeReader; + + public ControlTreeService() + : this(new UiAutomationService(), new MsaaTreeReader(), new Win32TreeReader()) + { + } + + public ControlTreeService( + UiAutomationService uiAutomationService, + MsaaTreeReader msaaTreeReader, + Win32TreeReader win32TreeReader) + { + _uiAutomationService = uiAutomationService ?? throw new ArgumentNullException("uiAutomationService"); + _msaaTreeReader = msaaTreeReader ?? throw new ArgumentNullException("msaaTreeReader"); + _win32TreeReader = win32TreeReader ?? throw new ArgumentNullException("win32TreeReader"); + } + + /// Root window. + /// + /// Optional UIA root: when the user picked a control inside a window, the UIA tree is read + /// from that element so the existing pick-then-inspect behaviour is preserved. MSAA and Win32 + /// always read from the window handle. + /// + /// null selects auto mode. + public ControlTreeResult Read( + IntPtr handle, + AutomationElement uiaRoot, + ControlTreeSource? source, + ControlTreeOptions options, + CancellationToken cancellationToken) + { + if (options == null) + { + options = new ControlTreeOptions(); + } + + if (handle == IntPtr.Zero) + { + return new ControlTreeResult + { + Succeeded = false, + Note = "HWND 为空。", + Root = null + }; + } + + if (source.HasValue) + { + return ReadOne(handle, uiaRoot, source.Value, options, cancellationToken, null); + } + + ControlTreeResult last = null; + foreach (ControlTreeSource candidate in AutoOrder) + { + cancellationToken.ThrowIfCancellationRequested(); + ControlTreeResult result = ReadOne(handle, uiaRoot, candidate, options, cancellationToken, last); + if (result.Succeeded) + { + if (last != null && last.Root != null) + { + result.Note = candidate + " 来源读到了内容;前面尝试的 " + + last.UsedSource + " 只有根节点。" + (result.Note ?? string.Empty); + } + + return result; + } + + last = result; + } + + return last ?? new ControlTreeResult { Succeeded = false, Note = "没有可用的来源。" }; + } + + private static readonly ControlTreeSource[] AutoOrder = + { + ControlTreeSource.Uia, + ControlTreeSource.Msaa, + ControlTreeSource.Win32 + }; + + private ControlTreeResult ReadOne( + IntPtr handle, + AutomationElement uiaRoot, + ControlTreeSource source, + ControlTreeOptions options, + CancellationToken cancellationToken, + ControlTreeResult previous) + { + var stopwatch = Stopwatch.StartNew(); + ControlTreeNode root; + string sourceNote = null; + try + { + switch (source) + { + case ControlTreeSource.Msaa: + root = _msaaTreeReader.Read(handle, options, cancellationToken); + break; + case ControlTreeSource.Win32: + root = _win32TreeReader.Read(handle, options, cancellationToken); + break; + default: + root = ReadUia(handle, uiaRoot, options, cancellationToken, out sourceNote); + break; + } + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + AppLog.Error("控件树读取失败(" + source + ")。", ex); + return new ControlTreeResult + { + UsedSource = source, + Succeeded = false, + Note = source + " 读取异常:" + ex.GetType().Name + ": " + ex.Message + }; + } + + stopwatch.Stop(); + int nodeCount = CountNodes(root); + bool hasContent = nodeCount > 1; + AppLog.Info(string.Format( + "控件树({0}):节点 {1} 个,耗时 {2} ms{3}。", + source, + nodeCount, + stopwatch.ElapsedMilliseconds, + root != null && !root.ChildrenComplete ? ";不完整:" + root.ChildrenError : string.Empty)); + + string note = sourceNote; + if (!hasContent) + { + note = source == ControlTreeSource.Uia + ? "UIA 只暴露了窗口本身(没有任何子控件)。" + : source + " 没有读到子节点。"; + } + else if (previous != null && !previous.Succeeded) + { + note = source + " 读到了内容;" + previous.UsedSource + " 没有。"; + } + + return new ControlTreeResult + { + Root = root, + UsedSource = source, + Succeeded = hasContent, + NodeCount = nodeCount, + Note = note + }; + } + + private ControlTreeNode ReadUia( + IntPtr handle, + AutomationElement uiaRoot, + ControlTreeOptions options, + CancellationToken cancellationToken, + out string note) + { + note = null; + UiaTreeNodeInfo uiaTree = uiaRoot != null + ? _uiAutomationService.ReadTree(uiaRoot, options.MaxDepth, options.MaxNodes, options.Timeout, cancellationToken) + : _uiAutomationService.ReadTree(handle, options.MaxDepth, options.MaxNodes, options.Timeout, cancellationToken); + ControlTreeNode tree = FromUia(uiaTree); + + // A UWP window (设置/计算器...) or a browser shell builds its content tree asynchronously: + // a read that lands right after the window appears often returns the chrome only. One + // bounded re-read usually picks up the content that has appeared by then. + if (uiaRoot == null && LooksLikeChromeOnly(tree)) + { + AppLog.Info("控件树只读到窗口边框(" + CountNodes(tree) + " 个节点),稍后重读一次。"); + Thread.Sleep(ChromeContentRetryDelayMs); + UiaTreeNodeInfo retry = _uiAutomationService.ReadTree( + handle, options.MaxDepth, options.MaxNodes, options.Timeout, cancellationToken); + ControlTreeNode retryTree = FromUia(retry); + if (CountNodes(retryTree) > CountNodes(tree)) + { + note = string.Format("首次只读到窗口边框({0} 个节点),等待 {1}ms 重读后拿到 {2} 个节点。", + CountNodes(tree), ChromeContentRetryDelayMs, CountNodes(retryTree)); + tree = retryTree; + } + } + + // The real content can also hang under a nested window element (UWP CoreWindow, renderer + // window). Reading that child is what the operator actually asked for. + if (uiaRoot == null && LooksLikeChromeOnly(tree)) + { + IntPtr contentWindow = _uiAutomationService.FindNestedContentWindow(handle); + if (contentWindow != IntPtr.Zero) + { + UiaTreeNodeInfo inner = _uiAutomationService.ReadTree( + contentWindow, options.MaxDepth, options.MaxNodes, options.Timeout, cancellationToken); + ControlTreeNode innerTree = FromUia(inner); + if (CountNodes(innerTree) > CountNodes(tree)) + { + note = string.Format( + "顶层窗口只暴露了标题栏({0} 个节点);已自动改读内层内容窗口 {1}({2} 个节点)。", + CountNodes(tree), NativeWindowInfo.FormatHandle(contentWindow), CountNodes(innerTree)); + return innerTree; + } + } + } + + 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. + /// + private static bool LooksLikeChromeOnly(ControlTreeNode tree) + { + if (tree == null) + { + return false; + } + + int nodeCount = CountNodes(tree); + if (nodeCount > 8) + { + return false; + } + + return ContainsControlType(tree, "ControlType.TitleBar"); + } + + private static bool ContainsControlType(ControlTreeNode node, string controlType) + { + if (node == null) + { + return false; + } + + if (node.Uia != null && string.Equals(node.Uia.ControlType, controlType, StringComparison.Ordinal)) + { + return true; + } + + foreach (ControlTreeNode child in node.Children) + { + if (ContainsControlType(child, controlType)) + { + return true; + } + } + + return false; + } + + public static ControlTreeNode FromUia(UiaTreeNodeInfo node) + { + if (node == null) + { + return null; + } + + var result = new ControlTreeNode + { + Source = ControlTreeSource.Uia, + Uia = node.Element, + ChildrenComplete = node.ChildrenComplete, + ChildrenError = node.ChildrenError + }; + foreach (UiaTreeNodeInfo child in node.Children) + { + ControlTreeNode converted = FromUia(child); + if (converted != null) + { + result.Children.Add(converted); + } + } + + return result; + } + + public static int CountNodes(ControlTreeNode node) + { + if (node == null) + { + return 0; + } + + int count = 1; + foreach (ControlTreeNode child in node.Children) + { + count += CountNodes(child); + } + + return count; + } + + /// Depth-first search for the first UIA node, used by the monitor editor. + public static UiaElementInfo FindFirstUiaElement(ControlTreeNode node) + { + if (node == null) + { + return null; + } + + if (node.Source == ControlTreeSource.Uia && node.Uia != null) + { + return node.Uia; + } + + foreach (ControlTreeNode child in node.Children) + { + UiaElementInfo found = FindFirstUiaElement(child); + if (found != null) + { + return found; + } + } + + return null; + } + + 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 new file mode 100644 index 0000000..d87ace9 --- /dev/null +++ b/src/pacs_win_uia/Services/ControlValueReader.cs @@ -0,0 +1,373 @@ +using System; +using System.Collections.Generic; +using System.Windows.Automation; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// Reads the property named by a saved ValueKey from a resolved control. Shared by the + /// editor (to prefill the current value) and the headless reader, so the two always agree on what + /// a key means. + /// + public static class ControlValueReader + { + /// + /// Reads a key. Returns false with a reason when the key is not supported by that source or + /// the provider refused it — "control found but no such property" must stay distinguishable + /// from "control not found". + /// + public static bool TryRead(ControlTreeNode node, string valueKey, ListReadOptions options, out string value, out string error) + { + value = null; + error = null; + if (node == null) + { + error = "控件为空。"; + return false; + } + + if (string.IsNullOrEmpty(valueKey)) + { + error = "没有设置属性名(valueKey)。"; + return false; + } + + switch (node.Source) + { + case ControlTreeSource.Msaa: + return TryReadMsaa(node.Msaa, valueKey, out value, out error); + case ControlTreeSource.Win32: + return TryReadWin32(node.Window, valueKey, out value, out error); + default: + return TryReadUia(node.Uia, valueKey, options, out value, out error); + } + } + + private static bool TryReadUia(UiaElementInfo info, string key, ListReadOptions options, out string value, out string error) + { + value = null; + error = null; + if (info == null) + { + error = "UIA 节点为空。"; + return false; + } + + switch (key) + { + case "Name": + value = info.Name; + break; + case "AutomationId": + value = info.AutomationId; + break; + case "ControlType": + value = info.ControlType; + break; + case "ClassName": + value = info.ClassName; + break; + case "FrameworkId": + value = info.FrameworkId; + break; + case "RuntimeId": + value = info.RuntimeId; + break; + case "IsEnabled": + value = info.IsEnabled.HasValue ? info.IsEnabled.Value.ToString() : null; + break; + case "IsOffscreen": + value = info.IsOffscreen.HasValue ? info.IsOffscreen.Value.ToString() : null; + break; + case "BoundingRectangle": + value = info.BoundingRectangle == null ? null : info.BoundingRectangle.ToString(); + break; + case "Value": + case "Text": + return TryReadUiaPatternValue(info, key, options, out value, out error); + case ControlValueKeys.Selected: + case "IsSelected": + return TryReadUiaSelected(info, key, out value, out error); + case ControlValueKeys.Focused: + case "HasKeyboardFocus": + return TryReadUiaFocus(info, key, out value, out error); + default: + error = "UIA 不支持的属性名:" + key + ";可用:" + string.Join(",", ControlValueKeys.Uia); + return false; + } + + if (value == null) + { + error = "该属性为空(控件存在,但没有值)。"; + return false; + } + + return true; + } + + /// Value/Text need live pattern calls, so they are only attempted when asked for. + private static bool TryReadUiaPatternValue(UiaElementInfo info, string key, ListReadOptions options, out string value, out string error) + { + value = null; + error = null; + AutomationElement element = info.Element; + if (element == null) + { + error = "UIA 元素引用不可用(可能是回读时未重新绑定)。"; + return false; + } + + try + { + object patternObject; + if (string.Equals(key, "Value", StringComparison.Ordinal)) + { + if (!element.TryGetCurrentPattern(ValuePattern.Pattern, out patternObject)) + { + error = "该控件不支持 ValuePattern。"; + return false; + } + + value = ((ValuePattern)patternObject).Current.Value; + return value != null; + } + + if (!element.TryGetCurrentPattern(TextPattern.Pattern, out patternObject)) + { + error = "该控件不支持 TextPattern。"; + return false; + } + + int maxLength = options == null ? 32768 : options.MaxTextLength; + value = ((TextPattern)patternObject).DocumentRange.GetText(Math.Max(1, maxLength)); + if (value != null) + { + value = value.TrimEnd('\r', '\n'); + } + + return value != null; + } + catch (Exception ex) + { + error = "读取 " + key + " 失败:" + ex.GetType().Name + ": " + ex.Message; + return false; + } + } + + /// Whether this element is the selected one; needs SelectionItemPattern. + private static bool TryReadUiaSelected(UiaElementInfo info, string key, out string value, out string error) + { + value = null; + error = null; + if (info.Element == null) + { + error = "UIA 元素引用不可用(可能是回读时未重新绑定)。"; + return false; + } + + try + { + object patternObject; + if (!info.Element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out patternObject)) + { + error = "该控件不支持 SelectionItemPattern,无法判断是否被选中(列表行/列表项通常支持)。"; + return false; + } + + bool selected = ((SelectionItemPattern)patternObject).Current.IsSelected; + value = string.Equals(key, "IsSelected", StringComparison.Ordinal) + ? selected.ToString() + : (selected ? "是" : "否"); + return true; + } + catch (Exception ex) + { + error = "读取选中状态失败:" + ex.GetType().Name + ": " + ex.Message; + return false; + } + } + + private static string DescribeMsaaSelection(MsaaNodeInfo info) + { + string state = info.StateText ?? string.Empty; + if (state.IndexOf("已选中", StringComparison.Ordinal) >= 0) + { + return "是"; + } + + return state.IndexOf("有焦点", StringComparison.Ordinal) >= 0 ? "有焦点但未选中" : "否"; + } + + /// Whether the element has keyboard focus; UIA exposes this as a plain property. + private static bool TryReadUiaFocus(UiaElementInfo info, string key, out string value, out string error) + { + value = null; + error = null; + if (!info.HasKeyboardFocus.HasValue) + { + error = "该控件的快照没有读到焦点状态(Provider 未暴露 HasKeyboardFocus)。"; + return false; + } + + bool focused = info.HasKeyboardFocus.Value; + if (string.Equals(key, "HasKeyboardFocus", StringComparison.Ordinal)) + { + value = focused.ToString(); + return true; + } + + if (focused) + { + value = "有焦点"; + return true; + } + + value = info.IsKeyboardFocusable.HasValue && !info.IsKeyboardFocusable.Value + ? "否(该控件不可获得焦点)" + : "无焦点"; + return true; + } + + private static string DescribeMsaaFocus(MsaaNodeInfo info) + { + string state = info.StateText ?? string.Empty; + return state.IndexOf("有焦点", StringComparison.Ordinal) >= 0 ? "有焦点" : "无焦点"; + } + + /// + /// 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. + /// + private static bool TryReadWin32Focus(NativeWindowInfo info, out string value, out string error) + { + value = null; + error = null; + try + { + IntPtr foreground = pacs_win_uia.Interop.NativeMethods.GetForegroundWindow(); + if (foreground == IntPtr.Zero) + { + error = "无法取得前台窗口。"; + return false; + } + + value = foreground == info.Handle ? "有焦点(前台窗口)" : "无焦点(不是前台窗口)"; + return true; + } + catch (Exception ex) + { + error = "读取前台窗口失败:" + ex.GetType().Name + ": " + ex.Message; + return false; + } + } + + private static bool TryReadMsaa(MsaaNodeInfo info, string key, out string value, out string error) + { + value = null; + error = null; + if (info == null) + { + error = "MSAA 节点为空。"; + return false; + } + + switch (key) + { + case "accName": + value = info.Name; + break; + case "accValue": + value = info.Value; + break; + case "accRole": + value = info.RoleText; + break; + case "accState": + value = info.StateText; + break; + case "accDescription": + value = info.Description; + break; + case "accDefaultAction": + value = info.DefaultAction; + break; + case "PathKey": + value = info.PathKey; + break; + case ControlValueKeys.Selected: + value = DescribeMsaaSelection(info); + break; + case ControlValueKeys.Focused: + value = DescribeMsaaFocus(info); + break; + default: + error = "MSAA 不支持的属性名:" + key + ";可用:" + string.Join(",", ControlValueKeys.Msaa); + return false; + } + + if (string.IsNullOrEmpty(value)) + { + error = "该属性为空(控件存在,但没有值)。"; + return false; + } + + return true; + } + + private static bool TryReadWin32(NativeWindowInfo info, string key, out string value, out string error) + { + value = null; + error = null; + if (info == null) + { + error = "Win32 窗口为空。"; + return false; + } + + switch (key) + { + case "窗口标题": + value = info.Title; + break; + case "类名": + value = info.ClassName; + break; + case "HWND": + value = info.HwndHex; + break; + case "窗口矩形": + value = info.WindowBounds == null ? null : info.WindowBounds.ToString(); + break; + case "客户区矩形": + value = info.ClientBounds == null ? null : info.ClientBounds.ToString(); + break; + case "可见": + value = info.IsVisible ? "是" : "否"; + break; + case "最小化": + value = info.IsMinimized ? "是" : "否"; + break; + case "进程名": + value = info.ProcessName; + break; + case "PID": + value = info.ProcessId.ToString(); + break; + case ControlValueKeys.Focused: + return TryReadWin32Focus(info, out value, out error); + default: + error = "Win32 不支持的属性名:" + key + ";可用:" + string.Join(",", ControlValueKeys.Win32); + return false; + } + + if (string.IsNullOrEmpty(value)) + { + error = "该属性为空(窗口存在,但这个属性没有值)。"; + return false; + } + + return true; + } + } +} diff --git a/src/pacs_win_uia/Services/HeadlessConfigReader.cs b/src/pacs_win_uia/Services/HeadlessConfigReader.cs new file mode 100644 index 0000000..13a127c --- /dev/null +++ b/src/pacs_win_uia/Services/HeadlessConfigReader.cs @@ -0,0 +1,303 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// Runs a saved monitor config without any UI and reports what could be read. + /// + /// It never invents data: a control that cannot be located is reported as not found, and a control + /// that is found but whose value cannot be read is reported with Found = true and + /// ValueAvailable = false, plus the reason. + /// + 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()) + { + } + + public HeadlessConfigReader( + ControlMonitorStore store, + ControlLocatorService locatorService, + NativeWindowService windowService) + { + _store = store ?? throw new ArgumentNullException("store"); + _locatorService = locatorService ?? throw new ArgumentNullException("locatorService"); + _windowService = windowService ?? throw new ArgumentNullException("windowService"); + } + + /// How long to keep waiting for a target window to appear. + /// Ask targets to switch their accessibility support on first. + public HeadlessReport Read(string configPath, TimeSpan windowTimeout, bool activate, CancellationToken cancellationToken) + { + var stopwatch = Stopwatch.StartNew(); + var report = new HeadlessReport + { + ReadAtUtc = DateTime.UtcNow, + ConfigPath = configPath + }; + + IList definitions = _store.Load(); + AppLog.Info("无界面读取:配置 " + configPath + ",共 " + definitions.Count + " 条定义。"); + foreach (NativeWindowInfo window in _windowService.EnumerateTopLevelWindows(false)) + { + report.Windows.Add(new HeadlessWindowInfo + { + Hwnd = window.HwndHex, + ProcessName = window.ProcessName, + ProcessId = window.ProcessId, + ClassName = window.ClassName, + Title = window.Title + }); + } + + AccessibilityActivationService activation = activate ? new AccessibilityActivationService() : null; + try + { + foreach (ControlMonitorDefinition definition in definitions) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!definition.Enabled) + { + // Kept in the config but deliberately not read. + report.Summary.Skipped++; + AppLog.Info("跳过已停用的条目:" + definition.ContentKey); + continue; + } + + report.Items.Add(ReadItem(definition, windowTimeout, activation, cancellationToken)); + } + } + finally + { + if (activation != null) + { + activation.Dispose(); + } + } + + report.Summary.Total = definitions.Count; + foreach (HeadlessItemResult item in report.Items) + { + if (!item.Found) + { + report.Summary.Missing++; + } + else if (!item.ValueAvailable) + { + report.Summary.ValueUnavailable++; + } + else + { + report.Summary.Found++; + } + } + + stopwatch.Stop(); + report.ElapsedMs = stopwatch.ElapsedMilliseconds; + AppLog.Info(string.Format( + "无界面读取完成:共 {0} 条(停用跳过 {1});命中 {2};未定位到 {3};定位到但取不到值 {4};耗时 {5} ms。", + report.Summary.Total, report.Summary.Skipped, report.Summary.Found, report.Summary.Missing, + report.Summary.ValueUnavailable, report.ElapsedMs)); + return report; + } + + private HeadlessItemResult ReadItem( + ControlMonitorDefinition definition, + TimeSpan windowTimeout, + AccessibilityActivationService activation, + CancellationToken cancellationToken) + { + var stopwatch = Stopwatch.StartNew(); + var steps = new List(); + var item = new HeadlessItemResult + { + ContentKey = definition.ContentKey, + ControlPath = definition.ControlPath, + PageFeatures = definition.PageFeatures, + RequestedSource = definition.Source.ToString(), + ValueKey = definition.ValueKey, + Resolution = steps + }; + + // Per-entry timeout wins; the global --timeout is only the fallback. + TimeSpan effectiveTimeout = definition.TimeoutSeconds > 0 + ? TimeSpan.FromSeconds(definition.TimeoutSeconds) + : windowTimeout; + if (definition.TimeoutSeconds > 0) + { + steps.Add("使用该条目自己的等待超时 " + definition.TimeoutSeconds + " 秒。"); + } + + IntPtr windowHandle = WaitForWindow(definition, effectiveTimeout, steps, cancellationToken); + if (windowHandle == IntPtr.Zero) + { + item.Found = false; + item.Error = "在 " + effectiveTimeout.TotalSeconds + " 秒内没有找到匹配的顶层窗口。"; + stopwatch.Stop(); + item.ElapsedMs = stopwatch.ElapsedMilliseconds; + AppLog.Warn("条目 " + definition.ContentKey + ":" + item.Error); + return item; + } + + if (activation != null) + { + steps.Add(activation.Activate(windowHandle)); + Thread.Sleep(BlockingActivationWaitMs); + } + + ControlResolution resolution = _locatorService.Resolve(definition, windowHandle, steps); + item.ResolvedSource = resolution.Found ? resolution.ResolvedSource.ToString() : null; + item.Found = resolution.Found; + item.Attributes = BuildAttributes(resolution.Node); + + if (!resolution.Found) + { + item.Error = resolution.Error; + stopwatch.Stop(); + item.ElapsedMs = stopwatch.ElapsedMilliseconds; + AppLog.Warn("条目 " + definition.ContentKey + " 未定位到:" + item.Error); + return item; + } + + string value; + string valueError; + if (ControlValueReader.TryRead(resolution.Node, definition.ValueKey, new ListReadOptions(), out value, out valueError)) + { + item.Value = value; + item.ValueAvailable = true; + steps.Add("按 " + definition.ValueKey + " 取值成功。"); + } + else + { + item.ValueAvailable = false; + item.Error = "控件已定位到,但取值失败:" + valueError; + steps.Add(item.Error); + AppLog.Warn("条目 " + definition.ContentKey + ":" + item.Error); + } + + stopwatch.Stop(); + item.ElapsedMs = stopwatch.ElapsedMilliseconds; + AppLog.Info(string.Format("条目 {0}:来源 {1};valueKey={2};找到={3};值可用={4};耗时 {5} ms。", + definition.ContentKey, item.ResolvedSource, item.ValueKey, item.Found, item.ValueAvailable, item.ElapsedMs)); + return item; + } + + private const int BlockingActivationWaitMs = 800; + + private IntPtr WaitForWindow( + ControlMonitorDefinition definition, + TimeSpan windowTimeout, + IList steps, + CancellationToken cancellationToken) + { + var stopwatch = Stopwatch.StartNew(); + string lastError = null; + int attempt = 0; + do + { + cancellationToken.ThrowIfCancellationRequested(); + attempt++; + string error; + IntPtr handle = _locatorService.FindTargetWindow(definition, steps, out error); + if (handle != IntPtr.Zero) + { + return handle; + } + + lastError = error; + if (stopwatch.Elapsed >= windowTimeout) + { + break; + } + + AppLog.Info("等待目标窗口(第 " + attempt + " 次):" + error); + Thread.Sleep(WindowPollIntervalMs); + } + while (stopwatch.Elapsed < windowTimeout); + + steps.Add("等待 " + windowTimeout.TotalSeconds + " 秒后仍未找到窗口:" + lastError); + return IntPtr.Zero; + } + + private const int WindowPollIntervalMs = 500; + + private static HeadlessAttributes BuildAttributes(ControlTreeNode node) + { + if (node == null) + { + return null; + } + + switch (node.Source) + { + case ControlTreeSource.Msaa: + if (node.Msaa == null) + { + return null; + } + + return new HeadlessAttributes + { + Name = node.Msaa.Name, + Role = node.Msaa.RoleText, + ClassName = null, + Hwnd = node.Msaa.WindowHandle == 0 ? null : "0x" + node.Msaa.WindowHandle.ToString("X"), + Bounds = node.Msaa.Location == null ? null : node.Msaa.Location.ToString(), + IsOffscreen = node.Msaa.StateText != null && + node.Msaa.StateText.IndexOf("屏幕外", StringComparison.Ordinal) >= 0 + ? (bool?)true + : null + }; + case ControlTreeSource.Win32: + if (node.Window == null) + { + return null; + } + + return new HeadlessAttributes + { + Name = node.Window.Title, + ClassName = node.Window.ClassName, + WindowTitle = node.Window.Title, + ProcessName = node.Window.ProcessName, + ProcessId = node.Window.ProcessId, + Hwnd = node.Window.HwndHex, + Bounds = node.Window.WindowBounds == null ? null : node.Window.WindowBounds.ToString() + }; + default: + if (node.Uia == null) + { + return null; + } + + return new HeadlessAttributes + { + Name = node.Uia.Name, + ControlType = node.Uia.ControlType, + ClassName = node.Uia.ClassName, + AutomationId = node.Uia.AutomationId, + ProcessId = node.Uia.ProcessId, + Hwnd = node.Uia.NativeWindowHandle == 0 ? null : "0x" + node.Uia.NativeWindowHandle.ToString("X"), + Bounds = node.Uia.BoundingRectangle == null ? null : node.Uia.BoundingRectangle.ToString(), + IsOffscreen = node.Uia.IsOffscreen, + IsEnabled = node.Uia.IsEnabled + }; + } + } + } +} diff --git a/src/pacs_win_uia/Services/ListReaderService.cs b/src/pacs_win_uia/Services/ListReaderService.cs new file mode 100644 index 0000000..4c8ce59 --- /dev/null +++ b/src/pacs_win_uia/Services/ListReaderService.cs @@ -0,0 +1,2097 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; +using System.Windows.Automation; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// Reads only data exposed by standard UI Automation patterns. It never invokes actions such as + /// Select, Invoke or ValuePattern.SetValue. + /// + /// The picked element is usually the deepest element under the cursor (a cell or a row), so the + /// reader walks up through its ancestors looking for something table-like. When no Grid/Table + /// pattern exists anywhere in that chain it falls back to child-element traversal, which only + /// ever sees rows the provider has already realized. + /// + /// Timeouts are soft: a synchronous provider call cannot be forcibly interrupted in-process. + /// + public sealed class ListReaderService + { + /// UIA_DesktopControlTypeId; the root element type on providers that report it. + private const int DesktopControlTypeId = 50016; + + /// Stop reading cells after this many consecutive failures with no success at all. + 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; + private const int DescendantNodeBudget = 600; + private const int MaxDescendantTraversalAttempts = 25; + + public ListReadResult Read(AutomationElement element, ListReadOptions options, CancellationToken cancellationToken) + { + if (options == null) + { + options = new ListReadOptions(); + } + + ListReadResult result = NewResult(ListReadSource.Unknown); + if (element == null) + { + return Unsupported(result, "UIA 元素为空。"); + } + + try + { + ValidateOptions(options); + cancellationToken.ThrowIfCancellationRequested(); + Stopwatch stopwatch = Stopwatch.StartNew(); + + List candidates = BuildCandidateChain(element, options, result, stopwatch, cancellationToken); + AppLog.Debug("列表读取:候选元素 " + candidates.Count + " 个(含被拾取元素本身)。"); + + // Every pattern search runs before any traversal. A traversal can always "find" rows + // — a window's layout panels look like rows — so it must never pre-empt a real + // GridPattern/TablePattern that exists further up or further down. + ReadCandidate? resolved = ReadPatterns(candidates, result, options, stopwatch, cancellationToken); + if (resolved.HasValue && result.Rows.Count > 0 && CountAvailableValues(result) == 0) + { + TryRescueValuesWithTraversal(resolved.Value, result, options, stopwatch, cancellationToken); + } + + // Picks that land on a window or a page container have their list *below* them, + // which the ancestor chain can never reach. + if (!resolved.HasValue) + { + resolved = ReadDescendants(candidates, result, options, stopwatch, cancellationToken); + if (resolved.HasValue && result.Rows.Count > 0 && CountAvailableValues(result) == 0) + { + TryRescueValuesWithTraversal(resolved.Value, result, options, stopwatch, cancellationToken); + } + } + + // Only now the traversal fallbacks: upwards first, then downwards. + if (!resolved.HasValue) + { + resolved = ReadTraversalChain(candidates, result, options, stopwatch, cancellationToken); + } + + if (!resolved.HasValue) + { + resolved = ReadDescendantTraversal(candidates, result, options, stopwatch, cancellationToken); + } + + if (!resolved.HasValue) + { + AppLog.Warn("列表读取:候选元素、其上级 " + options.MaxAncestorDepth + + " 级、以及向下 " + DescendantDepth + " 层都没有找到可读取的列表。"); + return Unsupported(result, "被拾取元素、其上级元素、以及被拾取元素内部的子元素都没有暴露可读取的列表。"); + } + + ReadCandidate winner = resolved.Value; + result.ResolvedElementName = winner.Name; + result.ResolvedElementControlType = winner.ControlType; + if (winner.FromDescendant) + { + result.AncestorLevel = -winner.Level; + result.Notices.Add(string.Format( + "被拾取元素内部没有列表数据;已在被拾取元素内第 {0} 层的 {1} 上读取。", + winner.Level, + string.IsNullOrEmpty(winner.ControlType) ? "子元素" : winner.ControlType)); + } + else + { + result.AncestorLevel = winner.Level; + if (winner.Level > 0) + { + result.Notices.Add(string.Format( + "被拾取元素本身不是列表;已在向上第 {0} 级的 {1} 上读取。", + winner.Level, + string.IsNullOrEmpty(winner.ControlType) ? "上级元素" : winner.ControlType)); + } + } + + if (options.ReadSelection) + { + // Selection lives on the container, not on the cell the user clicked. + TryReadSelection(winner.Element, result, stopwatch, options, cancellationToken); + CompleteStatus(result); + } + + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + AppLog.Info(string.Format( + "列表读取完成:来源={0};状态={1};行={2}/{3};列={4};单元格={5};完整={6};提示={7};错误={8}。", + result.Source, + result.Status, + result.RowsRead, + result.TotalRowsKnown ? result.RowCount.ToString() : "未知", + result.ColumnCount, + result.CellsRead, + result.IsComplete ? "是" : "否", + result.Notices.Count, + result.Errors.Count)); + return result; + } + catch (OperationCanceledException) + { + AppLog.Info("列表读取已取消。"); + return MarkStopped(result, ListReadStatus.Canceled, "读取已取消。"); + } + catch (TimeoutException ex) + { + AppLog.Warn("列表读取超时:" + ex.Message); + return MarkStopped(result, ListReadStatus.TimedOut, string.IsNullOrEmpty(ex.Message) ? "列表读取超时。" : ex.Message); + } + catch (Exception ex) + { + AppLog.Error("列表读取失败。", ex); + return Failed(result, ex); + } + } + + private struct ReadCandidate + { + internal AutomationElement Element; + internal int Level; + internal string Name; + internal string ControlType; + internal bool IsTopLevelWindow; + internal bool FromDescendant; + internal long NativeWindowHandle; + + internal string Describe() + { + return (string.IsNullOrEmpty(ControlType) ? "未知类型" : ControlType) + + " / " + (string.IsNullOrEmpty(Name) ? "(无名称)" : Name); + } + } + + /// + /// 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. + /// + private static List BuildCandidateChain( + AutomationElement element, + ListReadOptions options, + ListReadResult result, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + var candidates = new List(); + AutomationElement current = element; + int originProcessId = -1; + bool crossProcessNoted = false; + + for (int level = 0; current != null; level++) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + var candidate = new ReadCandidate { Element = current, Level = level }; + try + { + UiaElementInfo snapshot = Snapshot(current); + candidate.Name = snapshot.Name; + candidate.ControlType = snapshot.ControlType; + candidate.NativeWindowHandle = snapshot.NativeWindowHandle; + candidate.IsTopLevelWindow = snapshot.NativeWindowHandle != 0 + && string.Equals(snapshot.ControlType, "ControlType.Window", StringComparison.Ordinal); + if (level == 0) + { + originProcessId = snapshot.ProcessId; + } + else if (!crossProcessNoted && originProcessId > 0 && snapshot.ProcessId > 0 && + snapshot.ProcessId != originProcessId) + { + crossProcessNoted = true; + result.Notices.Add(string.Format( + "向上查找第 {0} 级时跨过了进程边界({1} -> {2}),仍继续查找。", + level, + originProcessId, + snapshot.ProcessId)); + } + } + catch (Exception ex) when (!(ex is OperationCanceledException) && !(ex is TimeoutException)) + { + AppLog.Warn("列表读取:读取第 " + level + " 级候选元素的属性失败:" + FormatException(ex)); + } + + candidates.Add(candidate); + if (level >= options.MaxAncestorDepth || candidate.IsTopLevelWindow) + { + // Never look above the top-level window: what lies there is the desktop. + break; + } + + AutomationElement parent; + try + { + parent = TreeWalker.ControlViewWalker.GetParent(current); + } + catch (Exception ex) when (!(ex is OperationCanceledException) && !(ex is TimeoutException)) + { + result.Notices.Add("向上查找上级元素时中断:" + FormatException(ex)); + break; + } + + if (parent == null || IsDesktop(parent)) + { + break; + } + + current = parent; + } + + return candidates; + } + + /// Probes the picked element and its ancestors for a real list pattern. + private static ReadCandidate? ReadPatterns( + List candidates, + ListReadResult result, + ListReadOptions options, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + foreach (ReadCandidate candidate in candidates) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + AppLog.Debug("列表读取:探测第 " + candidate.Level + " 级的列表模式:" + candidate.Describe() + "。"); + bool readSucceeded; + try + { + readSucceeded = TryReadPatterns(candidate.Element, result, options, stopwatch, cancellationToken); + } + catch (ElementNotAvailableException ex) + { + // The element died while probing it; an ancestor may still be alive. + AppLog.Warn("列表读取:第 " + candidate.Level + " 级候选元素已失效。", ex); + readSucceeded = false; + } + + if (readSucceeded || result.Rows.Count > 0) + { + if (!readSucceeded) + { + // Rows were read before the element disappeared: keep what we have. + result.Notices.Add("读取过程中目标元素失效,已保留已读取的行。"); + } + + return candidate; + } + } + + return null; + } + + private static bool TryReadPatterns( + AutomationElement element, + ListReadResult result, + ListReadOptions options, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + object patternObject; + + // TablePattern first: it carries semantic row/column identity for real tables. + if (TryGetPattern(element, TablePattern.Pattern, out patternObject)) + { + var table = (TablePattern)patternObject; + int rowCount = TryReadCount(delegate { return table.Current.RowCount; }); + if (rowCount > 0) + { + result.Source = ListReadSource.UiaTablePattern; + ReadTable(table, result, options, stopwatch, cancellationToken); + return true; + } + } + + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + if (TryGetPattern(element, GridPattern.Pattern, out patternObject)) + { + var grid = (GridPattern)patternObject; + int rowCount = TryReadCount(delegate { return grid.Current.RowCount; }); + if (rowCount > 0) + { + result.Source = ListReadSource.UiaGridPattern; + ReadGrid(grid, result, options, stopwatch, cancellationToken); + return true; + } + } + + return false; + } + + /// + /// Traversal pass. A row element's children also look like a "row level", so the attempt that + /// 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, + ListReadOptions options, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + ListReadResult best = null; + ReadCandidate bestCandidate = default(ReadCandidate); + int bestColumns = 0; + int bestLevel = int.MaxValue; + + foreach (ReadCandidate candidate in candidates) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + if (IsControlNotContainer(candidate.ControlType)) + { + AppLog.Debug("列表遍历:跳过 " + candidate.ControlType + "(控件类元素不可能是列表容器)。"); + continue; + } + var attempt = NewResult(ListReadSource.UiaElementTraversal); + attempt.TotalRowsKnown = false; + if (!TryReadTraversal(candidate.Element, attempt, options, stopwatch, cancellationToken)) + { + continue; + } + + int columns = WidestRow(attempt); + AppLog.Debug(string.Format( + "列表读取:第 {0} 级遍历到 {1} 行、最宽 {2} 列。", + candidate.Level, + attempt.Rows.Count, + columns)); + + bool better = best == null + || columns > bestColumns + || (columns == bestColumns && candidate.Level < bestLevel); + if (better) + { + best = attempt; + bestCandidate = candidate; + bestColumns = columns; + bestLevel = candidate.Level; + } + + if (columns >= 2) + { + break; + } + } + + if (best == null || best.Rows.Count == 0) + { + return null; + } + + Adopt(result, best); + CompleteStatus(result); + result.Notices.Add(string.Format( + "已按子元素遍历降级读取(最宽 {0} 列){1}。", + bestColumns, + bestColumns < 2 ? ";未能识别多列结构,结果可能只是列表的一列或某个单元格" : string.Empty)); + return bestCandidate; + } + + /// + /// Looks for a readable list *inside* the picked element. Picking a whole window (or a page + /// container) is a normal thing to do, and the list is a descendant in that case; the ancestor + /// 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, + ListReadOptions options, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + if (candidates.Count == 0) + { + return null; + } + + // The topmost element of the chain covers every subtree below it. + ReadCandidate start = candidates[candidates.Count - 1]; + var budget = new TraversalState(DescendantNodeBudget, stopwatch, options.Timeout, cancellationToken); + var queue = new Queue(); + queue.Enqueue(new DescendantNode { Element = start.Element, Level = 0 }); + int visited = 0; + + while (queue.Count > 0) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + DescendantNode node = queue.Dequeue(); + visited++; + if (visited > DescendantNodeBudget) + { + AppLog.Warn("列表读取:向下查找达到节点上限 " + DescendantNodeBudget + "。"); + break; + } + + if (node.Level > 0) + { + object patternObject; + if (TryGetPattern(node.Element, TablePattern.Pattern, out patternObject)) + { + var table = (TablePattern)patternObject; + if (TryReadCount(delegate { return table.Current.RowCount; }) > 0) + { + result.Source = ListReadSource.UiaTablePattern; + ReadTable(table, result, options, stopwatch, cancellationToken); + return DescribeCandidate(node, start); + } + } + + if (TryGetPattern(node.Element, GridPattern.Pattern, out patternObject)) + { + var grid = (GridPattern)patternObject; + if (TryReadCount(delegate { return grid.Current.RowCount; }) > 0) + { + result.Source = ListReadSource.UiaGridPattern; + ReadGrid(grid, result, options, stopwatch, cancellationToken); + return DescribeCandidate(node, start); + } + } + } + + if (node.Level >= DescendantDepth) + { + continue; + } + + List children = EnumerateChildren(node.Element, budget); + foreach (AutomationElement child in children) + { + queue.Enqueue(new DescendantNode { Element = child, Level = node.Level + 1 }); + } + } + + return null; + } + + /// + /// Downward traversal search for lists that expose rows but no Grid/Table pattern (web-style + /// lists). Only descendants that can hold children are probed, the number of attempts is + /// 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. + /// + private static ReadCandidate? ReadDescendantTraversal( + List candidates, + ListReadResult result, + ListReadOptions options, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + if (candidates.Count == 0) + { + return null; + } + + ReadCandidate start = candidates[candidates.Count - 1]; + var budget = new TraversalState(DescendantNodeBudget, stopwatch, options.Timeout, cancellationToken); + var queue = new Queue(); + queue.Enqueue(new DescendantNode { Element = start.Element, Level = 0 }); + + ListReadResult best = null; + DescendantNode bestNode = default(DescendantNode); + int bestColumns = 0; + int attempts = 0; + + while (queue.Count > 0 && attempts < MaxDescendantTraversalAttempts) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + DescendantNode node = queue.Dequeue(); + if (node.Level > 0) + { + var attempt = NewResult(ListReadSource.UiaElementTraversal); + attempt.TotalRowsKnown = false; + attempts++; + if (TryReadTraversal(node.Element, attempt, options, stopwatch, cancellationToken) && + attempt.Rows.Count > 0) + { + int columns = WidestRow(attempt); + if (columns > bestColumns) + { + best = attempt; + bestNode = node; + bestColumns = columns; + } + + if (columns >= 2) + { + break; + } + } + } + + if (node.Level >= DescendantDepth) + { + continue; + } + + foreach (AutomationElement child in EnumerateChildren(node.Element, budget)) + { + queue.Enqueue(new DescendantNode { Element = child, Level = node.Level + 1 }); + } + } + + if (best == null) + { + return null; + } + + Adopt(result, best); + CompleteStatus(result); + result.Notices.Add(string.Format( + "在被拾取元素内部第 {0} 层通过子元素遍历降级读取(最宽 {1} 列){2}。", + bestNode.Level, + bestColumns, + bestColumns < 2 ? ";未识别出多列结构,结果可能只是列表的一列" : string.Empty)); + return DescribeCandidate(bestNode, start); + } + + private static ReadCandidate DescribeCandidate(DescendantNode node, ReadCandidate start) + { + var candidate = new ReadCandidate + { + Element = node.Element, + Level = node.Level, + FromDescendant = true, + Name = start.Name, + ControlType = start.ControlType, + NativeWindowHandle = start.NativeWindowHandle + }; + + try + { + AutomationElement.AutomationElementInformation info = node.Element.Current; + candidate.Name = info.Name; + candidate.ControlType = info.ControlType == null ? null : info.ControlType.ProgrammaticName; + candidate.NativeWindowHandle = info.NativeWindowHandle; + } + catch (Exception ex) + { + AppLog.Warn("列表读取:读取子元素信息失败:" + FormatException(ex)); + } + + return candidate; + } + + private struct DescendantNode + { + internal AutomationElement Element; + internal int Level; + } + + private static int WidestRow(ListReadResult result) + { + int widest = 0; + foreach (ListRowResult row in result.Rows) + { + widest = Math.Max(widest, row.Cells.Count); + } + + return widest; + } + + private static void ReadGrid( + GridPattern grid, + ListReadResult result, + ListReadOptions options, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + int totalRows = grid.Current.RowCount; + int totalColumns = grid.Current.ColumnCount; + int rows = Math.Min(totalRows, options.MaxRows); + int columns = Math.Min(totalColumns, options.MaxColumns); + result.RowCount = totalRows; + result.ColumnCount = totalColumns; + result.IsComplete = rows == totalRows && columns == totalColumns; + AddLimitError(result, rows != totalRows, columns != totalColumns); + ReadCells(result, rows, columns, stopwatch, options, cancellationToken, + delegate(int rowIndex, int columnIndex) { return ReadGridCell(grid, rowIndex, columnIndex, options); }); + CompleteStatus(result); + } + + private static void ReadTable( + TablePattern table, + ListReadResult result, + ListReadOptions options, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + int totalRows = table.Current.RowCount; + int totalColumns = table.Current.ColumnCount; + int rows = Math.Min(totalRows, options.MaxRows); + int columns = Math.Min(totalColumns, options.MaxColumns); + result.RowCount = totalRows; + result.ColumnCount = totalColumns; + result.IsComplete = rows == totalRows && columns == totalColumns; + AddLimitError(result, rows != totalRows, columns != totalColumns); + ReadCells(result, rows, columns, stopwatch, options, cancellationToken, + delegate(int rowIndex, int columnIndex) { return ReadTableCell(table, rowIndex, columnIndex, options); }); + CompleteStatus(result); + } + + private static void ReadCells( + ListReadResult result, + int rows, + int columns, + Stopwatch stopwatch, + ListReadOptions options, + CancellationToken cancellationToken, + Func readCell) + { + int consecutiveFailures = 0; + int successes = 0; + for (int rowIndex = 0; rowIndex < rows; rowIndex++) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + var row = new ListRowResult + { + RowIndex = rowIndex, + RowId = rowIndex.ToString(), + IsComplete = true + }; + // Add the row before provider calls so cancellation/timeout preserves + // cells already read in the current row. + result.Rows.Add(row); + result.RowsRead++; + for (int columnIndex = 0; columnIndex < columns; columnIndex++) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + ListCellResult cell = readCell(rowIndex, columnIndex); + row.Cells.Add(cell); + result.CellsRead++; + if (!cell.IsAvailable || !cell.ValueAvailable) + { + row.IsComplete = false; + result.IsComplete = false; + consecutiveFailures++; + if (!string.IsNullOrEmpty(cell.Error)) + { + AddError(result, "单元格 [" + rowIndex + "," + columnIndex + "]: " + cell.Error, options.MaxErrors); + } + } + else + { + successes++; + consecutiveFailures = 0; + } + + // A provider that fails every single call (the WinForms DataGridView bridge + // throws E_UNEXPECTED on every cell) would be hammered once per cell; stop early + // and report the limitation instead. + if (successes == 0 && consecutiveFailures >= MaxConsecutiveCellFailures) + { + ReportAllCellsUnreadable(result, consecutiveFailures); + return; + } + } + } + + if (successes == 0 && result.CellsRead > 0) + { + ReportAllCellsUnreadable(result, result.CellsRead); + } + } + + private static void ReportAllCellsUnreadable(ListReadResult result, int failureCount) + { + result.IsComplete = false; + result.Status = ListReadStatus.Partial; + result.Notices.Add(string.Format( + "已读到的 {0} 个单元格全部无法取值:目标 Provider 不支持逐单元格访问,这不代表列表没有数据。", + failureCount)); + } + + /// + /// Some providers expose GridPattern/TablePattern for counts but fail every per-cell call + /// (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. + /// + private static void TryRescueValuesWithTraversal( + ReadCandidate candidate, + ListReadResult result, + ListReadOptions options, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + if (result.Rows.Count == 0 || CountAvailableValues(result) > 0) + { + return; + } + + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + var rescue = NewResult(ListReadSource.UiaElementTraversal); + rescue.TotalRowsKnown = false; + + // A provider that just failed every GetItem call is often left unusable, so the element + // is re-bound from its HWND before traversing it. + AutomationElement element = Reacquire(candidate); + if (!TryReadTraversal(element, rescue, options, stopwatch, cancellationToken)) + { + return; + } + + if (CountAvailableValues(rescue) <= 0) + { + return; + } + + AppLog.Info("列表读取:GridPattern/TablePattern 的单元格读取全部失败,已改用子元素遍历取回 " + + CountAvailableValues(rescue) + " 个单元格值。"); + Adopt(result, rescue); + result.Notices.Add("GridPattern/TablePattern 未能提供单元格值,已改用子元素遍历降级读取。"); + CompleteStatus(result); + } + + /// Rebinds an element from its own HWND, falling back to the current reference. + private static AutomationElement Reacquire(ReadCandidate candidate) + { + if (candidate.NativeWindowHandle == 0) + { + return candidate.Element; + } + + try + { + AutomationElement rebound = AutomationElement.FromHandle(new IntPtr(candidate.NativeWindowHandle)); + if (rebound != null) + { + AppLog.Debug("列表读取:已按 HWND 0x" + candidate.NativeWindowHandle.ToString("X") + " 重新绑定候选元素。"); + return rebound; + } + } + catch (Exception ex) + { + AppLog.Warn("列表读取:按 HWND 重新绑定元素失败:" + FormatException(ex)); + } + + return candidate.Element; + } + + private static int CountAvailableValues(ListReadResult result) + { + int count = 0; + foreach (ListRowResult row in result.Rows) + { + foreach (ListCellResult cell in row.Cells) + { + if (cell.IsAvailable && cell.ValueAvailable) + { + count++; + } + } + } + + return count; + } + + private static void Adopt(ListReadResult target, ListReadResult source) + { + target.Source = source.Source; + target.RowCount = source.RowCount; + target.ColumnCount = source.ColumnCount; + target.RowsRead = source.RowsRead; + target.CellsRead = source.CellsRead; + target.TotalRowsKnown = source.TotalRowsKnown; + target.IsComplete = source.IsComplete; + target.ColumnNames.Clear(); + foreach (string name in source.ColumnNames) + { + target.ColumnNames.Add(name); + } + + target.Rows.Clear(); + foreach (ListRowResult row in source.Rows) + { + target.Rows.Add(row); + } + + foreach (string notice in source.Notices) + { + target.Notices.Add(notice); + } + } + + // ---------------------------------------------------------------- traversal fallback + + /// + /// Downgraded reading: walk down from the container to find the row level, then treat each + /// child of a row as a cell. Only rows the provider has already realized are visible, so the + /// result is never reported as complete. + /// + private static bool TryReadTraversal( + AutomationElement container, + ListReadResult result, + ListReadOptions options, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + if (IsControlNotContainer(TryReadControlTypeName(container))) + { + return false; + } + + var state = new TraversalState(options.MaxTraversalNodes, stopwatch, options.Timeout, cancellationToken); + var notices = new List(); + List rows = FindRowLevel(container, options.MaxTraversalDepth, state, notices); + if (rows == null || rows.Count == 0) + { + return false; + } + + result.Source = ListReadSource.UiaElementTraversal; + result.TotalRowsKnown = false; + result.IsComplete = false; + result.RowCount = rows.Count; + notices.Add("通过子元素遍历降级读取:只能获取当前已实现(可见/已滚动到)的行,行数不是逻辑总数。"); + + List columnNames = TryReadColumnNames(container, state, notices); + bool tabSplitNoted = false; + int widestRow = 0; + int rowIndex = 0; + foreach (AutomationElement rowElement in rows) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + if (rowIndex >= options.MaxRows) + { + result.IsComplete = false; + notices.Add("行数超过 MaxRows=" + options.MaxRows + ",只读取了前 " + rowIndex + " 行。"); + break; + } + + var row = new ListRowResult + { + RowIndex = rowIndex, + RowId = rowIndex.ToString(), + IsComplete = true + }; + result.Rows.Add(row); + result.RowsRead++; + foreach (ListCellResult cell in ReadTraversalRow(rowElement, rowIndex, options, state, notices, ref tabSplitNoted)) + { + row.Cells.Add(cell); + result.CellsRead++; + if (!cell.IsAvailable || !cell.ValueAvailable) + { + row.IsComplete = false; + result.IsComplete = false; + if (!string.IsNullOrEmpty(cell.Error)) + { + AddError(result, "单元格 [" + rowIndex + "," + cell.ColumnIndex + "]: " + cell.Error, options.MaxErrors); + } + } + } + + widestRow = Math.Max(widestRow, row.Cells.Count); + rowIndex++; + } + + result.ColumnCount = Math.Max(widestRow, columnNames == null ? 0 : columnNames.Count); + FillColumnNames(result, columnNames, result.ColumnCount); + + // A layout container's children also pass the shape tests (a window's stacked panels look + // exactly like rows), so a level whose rows carry no readable value at all is rejected + // rather than reported as a list of empty rows. + int readableRange = 0; + foreach (ListRowResult row in result.Rows) + { + foreach (ListCellResult cell in row.Cells) + { + if (cell.IsAvailable && cell.ValueAvailable) + { + readableRange++; + break; + } + } + } + + if (result.Rows.Count > 0 && readableRange * 2 < result.Rows.Count) + { + AppLog.Debug("列表遍历:该层级的 " + result.Rows.Count + " 个候选行里只有 " + + readableRange + " 个能读到值,判定为布局容器而不是列表。"); + return false; + } + + // A single cell's children are not a list: one row and one column means the traversal + // walked into some text-bearing element. Report "no list" rather than a 1x1 grid. + if (result.Rows.Count < 2 && widestRow < 2) + { + AppLog.Debug("列表遍历:只得到 " + result.Rows.Count + " 行 " + widestRow + " 列,不足以判定为列表。"); + return false; + } + + foreach (string notice in notices) + { + result.Notices.Add(notice); + } + + return result.Rows.Count > 0; + } + + private static List FindRowLevel( + AutomationElement start, + int maxDepth, + TraversalState state, + IList notices) + { + AutomationElement current = start; + for (int depth = 0; depth <= maxDepth && current != null; depth++) + { + List children = EnumerateChildren(current, state); + if (children.Count == 0) + { + return null; + } + + List rows; + if (TryGetRowLevel(children, state, out rows)) + { + return rows; + } + + AutomationElement next = FindDescentTarget(children, state); + if (next == null) + { + return null; + } + + current = next; + } + + return null; + } + + /// + /// A level counts as rows only when its children look like rows: headers, scrollbars and + /// other chrome are excluded (a minority of chrome must not disqualify the level), the rest + /// 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. + /// + private static bool TryGetRowLevel( + List children, + TraversalState state, + out List rows) + { + rows = null; + if (children == null || children.Count == 0) + { + return false; + } + + var candidates = new List(children.Count); + var types = new List(children.Count); + int denied = 0; + foreach (AutomationElement child in children) + { + string typeName = TryReadControlTypeName(child); + if (IsDeniedRowType(typeName)) + { + denied++; + continue; + } + + // A child built only out of header cells is a header band (typical for WinForms + // grids), not a data row. + if (IsHeaderBand(child, state)) + { + denied++; + continue; + } + + candidates.Add(child); + types.Add(typeName); + } + + // A header band or a scrollbar-only level is chrome, not a row level. + if (candidates.Count == 0 || denied > candidates.Count) + { + return false; + } + + string firstType = types[0]; + if (IsRowControlType(firstType)) + { + rows = candidates; + return true; + } + + int sameType = 0; + foreach (string typeName in types) + { + if (string.Equals(typeName, firstType, StringComparison.Ordinal)) + { + sameType++; + } + } + + if (sameType * 100 / candidates.Count < 80) + { + return false; + } + + object itemPattern; + if (TryGetPattern(candidates[0], SelectionItemPattern.Pattern, out itemPattern)) + { + rows = candidates; + return true; + } + + bool allNamed = true; + foreach (AutomationElement child in candidates) + { + if (string.IsNullOrEmpty(TryReadName(child))) + { + allNamed = false; + break; + } + } + + if (allNamed) + { + rows = candidates; + return true; + } + + // A single child whose own children sit side by side is a row (its cells), not a container. + if (candidates.Count == 1 && HasHorizontallyArrangedChildren(candidates[0], state)) + { + rows = candidates; + return true; + } + + if (IsVerticallyStacked(candidates)) + { + rows = candidates; + return true; + } + + return false; + } + + /// + /// 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". + /// + private static bool IsControlNotContainer(string controlTypeName) + { + if (string.IsNullOrEmpty(controlTypeName)) + { + return false; + } + + switch (controlTypeName) + { + case "ControlType.Button": + case "ControlType.Edit": + case "ControlType.Text": + case "ControlType.CheckBox": + case "ControlType.RadioButton": + case "ControlType.Hyperlink": + case "ControlType.ComboBox": + case "ControlType.MenuItem": + case "ControlType.TabItem": + case "ControlType.Slider": + case "ControlType.Spinner": + case "ControlType.ProgressBar": + case "ControlType.Image": + case "ControlType.SplitButton": + case "ControlType.Header": + case "ControlType.HeaderItem": + case "ControlType.ScrollBar": + case "ControlType.Thumb": + case "ControlType.ToolTip": + case "ControlType.TitleBar": + return true; + default: + return false; + } + } + + /// True when every child is a header cell: that element is a header band, not a row. + private static bool IsHeaderBand(AutomationElement element, TraversalState state) + { + List children = EnumerateChildren(element, state); + if (children.Count == 0) + { + return false; + } + + foreach (AutomationElement child in children) + { + if (!IsDeniedRowType(TryReadControlTypeName(child))) + { + return false; + } + } + + return true; + } + + private static bool HasHorizontallyArrangedChildren(AutomationElement parent, TraversalState state) + { + List children = EnumerateChildren(parent, state); + if (children.Count < 2) + { + return false; + } + + System.Windows.Rect first = TryReadBounds(children[0]); + System.Windows.Rect second = TryReadBounds(children[1]); + if (first.IsEmpty || second.IsEmpty) + { + return false; + } + + double tolerance = Math.Max(2D, first.Width / 4D); + return second.Left >= first.Right - tolerance; + } + + private static AutomationElement FindDescentTarget(List children, TraversalState state) + { + int examined = 0; + foreach (AutomationElement child in children) + { + if (examined >= 8) + { + break; + } + + examined++; + if (IsDeniedRowType(TryReadControlTypeName(child))) + { + continue; + } + + try + { + state.Spend(); + if (TreeWalker.ControlViewWalker.GetFirstChild(child) != null) + { + return child; + } + } + catch (Exception ex) when (!(ex is OperationCanceledException) && !(ex is TimeoutException)) + { + // A provider that refuses child queries simply is not the descent target. + } + } + + return null; + } + + private static bool IsVerticallyStacked(List children) + { + if (children.Count < 2) + { + return false; + } + + System.Windows.Rect first = TryReadBounds(children[0]); + System.Windows.Rect second = TryReadBounds(children[1]); + if (first.IsEmpty || second.IsEmpty) + { + return false; + } + + double tolerance = Math.Max(2D, first.Height / 4D); + return second.Top >= first.Bottom - tolerance; + } + + private static bool IsRowControlType(string controlTypeName) + { + return string.Equals(controlTypeName, "ControlType.ListItem", StringComparison.Ordinal) + || string.Equals(controlTypeName, "ControlType.DataItem", StringComparison.Ordinal) + || string.Equals(controlTypeName, "ControlType.TreeItem", StringComparison.Ordinal); + } + + /// Control types that are never rows and never a descent target. + private static bool IsDeniedRowType(string controlTypeName) + { + if (string.IsNullOrEmpty(controlTypeName)) + { + return false; + } + + switch (controlTypeName) + { + case "ControlType.Header": + case "ControlType.HeaderItem": + case "ControlType.ScrollBar": + case "ControlType.Thumb": + case "ControlType.TitleBar": + case "ControlType.Edit": + case "ControlType.Button": + case "ControlType.ComboBox": + case "ControlType.MenuBar": + case "ControlType.Menu": + case "ControlType.MenuItem": + case "ControlType.ToolBar": + case "ControlType.StatusBar": + case "ControlType.Separator": + return true; + default: + return false; + } + } + + private static List ReadTraversalRow( + AutomationElement rowElement, + int rowIndex, + ListReadOptions options, + TraversalState state, + IList notices, + ref bool tabSplitNoted) + { + var cells = new List(); + foreach (AutomationElement cellElement in EnumerateChildren(rowElement, state)) + { + // Row headers and other chrome are not data cells, and counting them would shift + // every column index. + if (IsDeniedRowType(TryReadControlTypeName(cellElement))) + { + continue; + } + + cells.Add(ReadTraversalCell(cellElement, rowIndex, cells.Count, options, state)); + } + + if (cells.Count > 0) + { + return cells; + } + + // No element-addressable cells: the row's own text is all the provider exposes. + string rowName = TryReadName(rowElement); + if (!string.IsNullOrEmpty(rowName) && rowName.IndexOf('\t') >= 0) + { + if (!tabSplitNoted) + { + tabSplitNoted = true; + notices.Add("部分行的文本以制表符分隔,已按制表符拆分为多列;这是降级推断,不是控件声明的列结构。"); + } + + string[] parts = rowName.Split('\t'); + for (int index = 0; index < parts.Length; index++) + { + cells.Add(new ListCellResult + { + RowIndex = rowIndex, + ColumnIndex = index, + RowId = rowIndex.ToString(), + ColumnId = index.ToString(), + Value = parts[index], + ValueSource = ListValueSource.Name, + ValueAvailable = true, + IsAvailable = true + }); + } + + return cells; + } + + cells.Add(new ListCellResult + { + RowIndex = rowIndex, + ColumnIndex = 0, + RowId = rowIndex.ToString(), + ColumnId = "0", + Value = rowName, + ValueSource = ListValueSource.Name, + ValueAvailable = rowName != null, + IsAvailable = true, + Error = rowName == null ? "行元素未暴露任何可读取值。" : null + }); + return cells; + } + + /// + /// 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. + /// + private static ListCellResult ReadTraversalCell( + AutomationElement cell, + int rowIndex, + int columnIndex, + ListReadOptions options, + TraversalState state) + { + var result = new ListCellResult + { + RowIndex = rowIndex, + ColumnIndex = columnIndex, + RowId = rowIndex.ToString(), + ColumnId = columnIndex.ToString(), + IsAvailable = true + }; + if (cell == null) + { + result.IsAvailable = false; + result.Error = "UIA 单元格为空。"; + return result; + } + + try + { + state.Spend(); + + // For an edit/document cell the accessibility Name is a label ("姓名 行 0, 未排序。"), + // not the content, so the value pattern has to be preferred there. + string typeName = TryReadControlTypeName(cell); + bool nameIsLabel = string.Equals(typeName, "ControlType.Edit", StringComparison.Ordinal) + || string.Equals(typeName, "ControlType.Document", StringComparison.Ordinal); + if (nameIsLabel && TryReadValuePattern(cell, out string labelledValue) && labelledValue != null) + { + result.Value = labelledValue; + result.ValueSource = ListValueSource.ValuePattern; + result.ValueAvailable = true; + return result; + } + + string name = TryReadName(cell); + if (!string.IsNullOrEmpty(name)) + { + result.Value = name; + result.ValueSource = ListValueSource.Name; + result.ValueAvailable = true; + return result; + } + + string value; + if (TryReadValuePattern(cell, out value)) + { + result.Value = value; + result.ValueSource = ListValueSource.ValuePattern; + result.ValueAvailable = value != null; + if (!result.ValueAvailable) + { + result.Error = "单元格元素存在,但未暴露可读取值。"; + } + + return result; + } + + if (TryReadTextPattern(cell, options, out value)) + { + result.Value = value; + result.ValueSource = ListValueSource.TextPattern; + result.ValueAvailable = value != null; + return result; + } + + // A cell in edit mode keeps its text in a child Edit control. + string editValue; + if (TryReadSingleEditChildValue(cell, state, out editValue)) + { + result.Value = editValue; + result.ValueSource = ListValueSource.ValuePattern; + result.ValueAvailable = true; + return result; + } + + result.Error = "单元格元素存在,但未暴露可读取值。"; + } + catch (OperationCanceledException) + { + throw; + } + catch (TimeoutException) + { + throw; + } + catch (Exception ex) + { + result.Error = FormatException(ex); + } + + return result; + } + + private static List TryReadColumnNames(AutomationElement container, TraversalState state, IList notices) + { + List names = TryReadPatternColumnHeaders(container); + if (names != null && names.Count > 0) + { + return names; + } + + names = TryReadHeaderChildNames(container, state); + if (names != null && names.Count > 0) + { + return names; + } + + notices.Add("未找到列头元素,列名使用 Column0..N 占位,可能不是真实列名。"); + return null; + } + + private static List TryReadPatternColumnHeaders(AutomationElement container) + { + // Only TablePattern exposes column headers; GridPattern has no header API. + object patternObject; + if (TryGetPattern(container, TablePattern.Pattern, out patternObject)) + { + List names = TryReadHeaderNames(delegate { return ((TablePattern)patternObject).Current.GetColumnHeaders(); }); + if (names.Count > 0) + { + return names; + } + } + + return null; + } + + private static List TryReadHeaderNames(Func getHeaders) + { + var names = new List(); + try + { + AutomationElement[] headers = getHeaders(); + if (headers == null) + { + return names; + } + + foreach (AutomationElement header in headers) + { + if (header == null) + { + continue; + } + + string name = header.Current.Name; + names.Add(name ?? string.Empty); + } + } + catch (Exception ex) when (!(ex is OperationCanceledException) && !(ex is TimeoutException)) + { + names.Clear(); + } + + return names; + } + + private static List TryReadHeaderChildNames(AutomationElement container, TraversalState state) + { + var names = new List(); + List children = EnumerateChildren(container, state); + foreach (AutomationElement child in children) + { + if (!string.Equals(TryReadControlTypeName(child), "ControlType.Header", StringComparison.Ordinal)) + { + continue; + } + + foreach (AutomationElement headerItem in EnumerateChildren(child, state)) + { + names.Add(TryReadName(headerItem) ?? string.Empty); + } + + return names; + } + + return names; + } + + private static void FillColumnNames(ListReadResult result, List columnNames, int columnCount) + { + result.ColumnNames.Clear(); + for (int index = 0; index < columnCount; index++) + { + string name = columnNames != null && index < columnNames.Count ? columnNames[index] : null; + result.ColumnNames.Add(string.IsNullOrEmpty(name) ? "Column" + index : name); + } + } + + private static List EnumerateChildren(AutomationElement parent, TraversalState state) + { + var children = new List(); + try + { + AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(parent); + while (child != null) + { + state.Spend(); + children.Add(child); + child = TreeWalker.ControlViewWalker.GetNextSibling(child); + } + } + catch (OperationCanceledException) + { + throw; + } + catch (TimeoutException) + { + throw; + } + catch (Exception ex) + { + AppLog.Warn("列表遍历:枚举子元素中断(已获取 " + children.Count + " 个):" + FormatException(ex)); + } + + return children; + } + + // ---------------------------------------------------------------- selection + + private static void TryReadSelection( + AutomationElement element, + ListReadResult result, + Stopwatch stopwatch, + ListReadOptions options, + CancellationToken cancellationToken) + { + try + { + object selectionObject; + if (!element.TryGetCurrentPattern(SelectionPattern.Pattern, out selectionObject)) + { + return; + } + + if (result.Status == ListReadStatus.Unsupported) + { + result.Source = ListReadSource.UiaSelectionPattern; + result.Status = ListReadStatus.Partial; + } + + SelectionPattern selection = (SelectionPattern)selectionObject; + AutomationElement[] selectedItems = selection.Current.GetSelection(); + if (selectedItems == null) + { + result.IsComplete = false; + AddError(result, "SelectionPattern 未返回选中项集合。", options.MaxErrors); + return; + } + + foreach (AutomationElement selected in selectedItems) + { + ThrowIfStopped(stopwatch, options.Timeout, cancellationToken); + try + { + string automationId = selected.Current.AutomationId; + result.SelectedItems.Add(new ListSelectionResult + { + Index = result.SelectedItems.Count, + RowId = automationId, + Name = selected.Current.Name, + AutomationId = automationId, + IsAvailable = true + }); + } + catch (OperationCanceledException) + { + throw; + } + catch (TimeoutException) + { + throw; + } + catch (Exception ex) + { + result.SelectedItems.Add(new ListSelectionResult + { + Index = result.SelectedItems.Count, + IsAvailable = false, + Error = FormatException(ex) + }); + AddError(result, "选中项: " + FormatException(ex), options.MaxErrors); + result.IsComplete = false; + } + } + } + catch (OperationCanceledException) + { + throw; + } + catch (TimeoutException) + { + throw; + } + catch (Exception ex) + { + result.IsComplete = false; + AddError(result, "SelectionPattern: " + FormatException(ex), options.MaxErrors); + } + } + + // ---------------------------------------------------------------- cells + + private static ListCellResult ReadGridCell(GridPattern grid, int rowIndex, int columnIndex, ListReadOptions options) + { + try + { + return ReadCell(grid.GetItem(rowIndex, columnIndex), rowIndex, columnIndex, options); + } + catch (OperationCanceledException) + { + throw; + } + catch (TimeoutException) + { + throw; + } + catch (Exception ex) + { + return FailedCell(rowIndex, columnIndex, ex); + } + } + + private static ListCellResult ReadTableCell(TablePattern table, int rowIndex, int columnIndex, ListReadOptions options) + { + try + { + return ReadCell(table.GetItem(rowIndex, columnIndex), rowIndex, columnIndex, options); + } + catch (OperationCanceledException) + { + throw; + } + catch (TimeoutException) + { + throw; + } + catch (Exception ex) + { + return FailedCell(rowIndex, columnIndex, ex); + } + } + + private static ListCellResult ReadCell(AutomationElement cell, int rowIndex, int columnIndex, ListReadOptions options) + { + var result = new ListCellResult + { + RowIndex = rowIndex, + ColumnIndex = columnIndex, + RowId = rowIndex.ToString(), + ColumnId = columnIndex.ToString() + }; + if (cell == null) + { + result.Error = "UIA 单元格为空。"; + return result; + } + + try + { + result.Value = ReadCellValue(cell, options, out ListValueSource source, out bool available); + result.ValueSource = source; + result.ValueAvailable = available; + result.IsAvailable = true; + if (!available) + { + result.Error = "单元格元素存在,但未暴露可读取值。"; + } + } + catch (OperationCanceledException) + { + throw; + } + catch (TimeoutException) + { + throw; + } + catch (Exception ex) + { + result.Error = FormatException(ex); + } + + return result; + } + + private static string ReadCellValue(AutomationElement cell, ListReadOptions options, out ListValueSource source, out bool available) + { + string value; + if (TryReadValuePattern(cell, out value)) + { + source = ListValueSource.ValuePattern; + available = value != null; + return value; + } + + if (TryReadTextPattern(cell, options, out value)) + { + source = ListValueSource.TextPattern; + available = value != null; + return value; + } + + string name = cell.Current.Name; + source = ListValueSource.Name; + available = name != null; + return name; + } + + private static bool TryReadValuePattern(AutomationElement element, out string value) + { + value = null; + object valueObject; + try + { + if (!element.TryGetCurrentPattern(ValuePattern.Pattern, out valueObject)) + { + return false; + } + + value = ((ValuePattern)valueObject).Current.Value; + return true; + } + catch (OperationCanceledException) + { + throw; + } + catch (TimeoutException) + { + throw; + } + catch + { + return false; + } + } + + private static bool TryReadTextPattern(AutomationElement element, ListReadOptions options, out string value) + { + value = null; + object textObject; + try + { + if (!element.TryGetCurrentPattern(TextPattern.Pattern, out textObject)) + { + return false; + } + + // Bounded read: an unbounded GetText(-1) would marshal a whole document across RPC. + value = ((TextPattern)textObject).DocumentRange.GetText(Math.Max(1, options.MaxTextLength)); + if (value != null) + { + value = value.TrimEnd('\r', '\n'); + } + + return true; + } + catch (OperationCanceledException) + { + throw; + } + catch (TimeoutException) + { + throw; + } + catch + { + return false; + } + } + + private static bool TryReadSingleEditChildValue(AutomationElement cell, TraversalState state, out string value) + { + value = null; + List children = EnumerateChildren(cell, state); + if (children.Count != 1) + { + return false; + } + + if (!string.Equals(TryReadControlTypeName(children[0]), "ControlType.Edit", StringComparison.Ordinal)) + { + return false; + } + + return TryReadValuePattern(children[0], out value); + } + + private static ListCellResult FailedCell(int rowIndex, int columnIndex, Exception exception) + { + return new ListCellResult + { + RowIndex = rowIndex, + ColumnIndex = columnIndex, + RowId = rowIndex.ToString(), + ColumnId = columnIndex.ToString(), + Error = FormatException(exception) + }; + } + + // ---------------------------------------------------------------- helpers + + private static bool TryGetPattern(AutomationElement element, AutomationPattern pattern, out object patternObject) + { + patternObject = null; + try + { + return element.TryGetCurrentPattern(pattern, out patternObject); + } + catch (Exception ex) when (!(ex is ElementNotAvailableException) && !(ex is OperationCanceledException) && !(ex is TimeoutException)) + { + return false; + } + } + + private static UiaElementInfo Snapshot(AutomationElement element) + { + var snapshot = new UiaElementInfo { Element = element }; + AutomationElement.AutomationElementInformation current = element.Current; + snapshot.Name = current.Name; + snapshot.ControlType = current.ControlType == null ? null : current.ControlType.ProgrammaticName; + snapshot.ProcessId = current.ProcessId; + snapshot.NativeWindowHandle = current.NativeWindowHandle; + return snapshot; + } + + private static string TryReadControlTypeName(AutomationElement element) + { + try + { + ControlType controlType = element.Current.ControlType; + return controlType == null ? null : controlType.ProgrammaticName; + } + catch (Exception ex) when (!(ex is OperationCanceledException) && !(ex is TimeoutException)) + { + return null; + } + } + + private static string TryReadName(AutomationElement element) + { + try + { + return element.Current.Name; + } + catch (Exception ex) when (!(ex is OperationCanceledException) && !(ex is TimeoutException)) + { + return null; + } + } + + private static System.Windows.Rect TryReadBounds(AutomationElement element) + { + try + { + return element.Current.BoundingRectangle; + } + catch (Exception ex) when (!(ex is OperationCanceledException) && !(ex is TimeoutException)) + { + return System.Windows.Rect.Empty; + } + } + + private static int TryReadCount(Func getter) + { + try + { + return getter(); + } + catch (Exception ex) when (!(ex is OperationCanceledException) && !(ex is TimeoutException)) + { + return 0; + } + } + + /// + /// The desktop must never be probed or descended into: enumerating its children walks every + /// window on the machine. The managed ControlType class has no Desktop member, and the root + /// element is commonly reported as a Pane with class "#32769", so identity against + /// RootElement is the reliable test. + /// + private static bool IsDesktop(AutomationElement element) + { + if (element == null) + { + return true; + } + + try + { + if (element == AutomationElement.RootElement) + { + return true; + } + + ControlType controlType = element.Current.ControlType; + return controlType != null && controlType.Id == DesktopControlTypeId; + } + catch + { + // Unreadable ancestors are treated as a stop: nothing beyond them is reachable anyway. + return true; + } + } + + + private static void ValidateOptions(ListReadOptions options) + { + if (options.MaxRows < 1) + { + throw new ArgumentOutOfRangeException("MaxRows"); + } + + if (options.MaxColumns < 1) + { + throw new ArgumentOutOfRangeException("MaxColumns"); + } + + if (options.MaxErrors < 0) + { + throw new ArgumentOutOfRangeException("MaxErrors"); + } + + if (options.Timeout < TimeSpan.Zero && options.Timeout != Timeout.InfiniteTimeSpan) + { + throw new ArgumentOutOfRangeException("Timeout"); + } + + if (options.MaxTraversalNodes < 1) + { + throw new ArgumentOutOfRangeException("MaxTraversalNodes"); + } + + if (options.MaxTraversalDepth < 0) + { + throw new ArgumentOutOfRangeException("MaxTraversalDepth"); + } + + if (options.MaxAncestorDepth < 0) + { + throw new ArgumentOutOfRangeException("MaxAncestorDepth"); + } + + if (options.MaxTextLength < 1) + { + throw new ArgumentOutOfRangeException("MaxTextLength"); + } + } + + private static void ThrowIfStopped(Stopwatch stopwatch, TimeSpan timeout, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (timeout != Timeout.InfiniteTimeSpan && stopwatch.Elapsed >= timeout) + { + throw new TimeoutException("列表读取超时。"); + } + } + + private static void CompleteStatus(ListReadResult result) + { + if (result.Status != ListReadStatus.Unsupported && result.Status != ListReadStatus.Failed && + result.Status != ListReadStatus.Canceled && result.Status != ListReadStatus.TimedOut) + { + result.Status = result.IsComplete ? ListReadStatus.Success : ListReadStatus.Partial; + } + } + + private static void AddLimitError(ListReadResult result, bool rowsLimited, bool columnsLimited) + { + if (rowsLimited || columnsLimited) + { + result.IsComplete = false; + result.Status = ListReadStatus.Partial; + result.Errors.Add("结果受到 MaxRows 或 MaxColumns 限制。"); + } + } + + private static void AddError(ListReadResult result, string error, int maxErrors) + { + if (maxErrors == 0 || result.Errors.Count < maxErrors) + { + result.Errors.Add(error); + } + } + + private static ListReadResult NewResult(ListReadSource source) + { + return new ListReadResult + { + Source = source, + Status = ListReadStatus.Partial, + IsComplete = true + }; + } + + private static ListReadResult Unsupported(ListReadResult result, string message) + { + result.Status = ListReadStatus.Unsupported; + result.IsComplete = false; + result.Error = message; + AddError(result, message, 1); + return result; + } + + private static ListReadResult Failed(ListReadResult result, Exception exception) + { + result.Status = ListReadStatus.Failed; + result.IsComplete = false; + result.Error = FormatException(exception); + AddError(result, result.Error, 1); + return result; + } + + private static ListReadResult MarkStopped(ListReadResult result, ListReadStatus status, string message) + { + result.Status = status; + result.IsComplete = false; + result.Error = message; + if (result.Errors.Count == 0) + { + result.Errors.Add(message); + } + + return result; + } + + private static string FormatException(Exception exception) + { + if (exception is ElementNotAvailableException) + { + return "ElementNotAvailable: " + exception.Message; + } + + if (exception is COMException) + { + return string.Format("COM 0x{0:X8}: {1}", exception.HResult, exception.Message); + } + + return exception.GetType().Name + ": " + exception.Message; + } + + /// Bounds the traversal by both a deadline and a node budget. + private sealed class TraversalState + { + private readonly Stopwatch _stopwatch; + private readonly TimeSpan _timeout; + private readonly CancellationToken _cancellationToken; + private int _remainingNodes; + + internal TraversalState(int maxNodes, Stopwatch stopwatch, TimeSpan timeout, CancellationToken cancellationToken) + { + _remainingNodes = maxNodes; + _stopwatch = stopwatch; + _timeout = timeout; + _cancellationToken = cancellationToken; + } + + internal void Spend() + { + _cancellationToken.ThrowIfCancellationRequested(); + if (_timeout != Timeout.InfiniteTimeSpan && _stopwatch.Elapsed >= _timeout) + { + throw new TimeoutException("列表遍历读取超时。"); + } + + if (_remainingNodes <= 0) + { + throw new TimeoutException("列表遍历达到 MaxTraversalNodes 节点上限,结果不完整。"); + } + + _remainingNodes--; + } + } + } +} diff --git a/src/pacs_win_uia/Services/ListResultExporter.cs b/src/pacs_win_uia/Services/ListResultExporter.cs new file mode 100644 index 0000000..043c4ce --- /dev/null +++ b/src/pacs_win_uia/Services/ListResultExporter.cs @@ -0,0 +1,261 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Runtime.Serialization.Json; +using System.Text; +using pacs_win_uia.Models; + +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. + /// + public sealed class ListResultExporter + { + private const int MaxCsvColumns = 10000; + + public string SerializeJson(ListReadResult result) + { + if (result == null) + { + throw new ArgumentNullException("result"); + } + + var serializer = new DataContractJsonSerializer(typeof(ListReadResult)); + using (var stream = new MemoryStream()) + { + serializer.WriteObject(stream, result); + return Encoding.UTF8.GetString(stream.ToArray()); + } + } + + public void ExportJson(ListReadResult result, string filePath) + { + WriteText(filePath, SerializeJson(result), new UTF8Encoding(false)); + } + + public string SerializeCsv(ListReadResult result) + { + if (result == null) + { + throw new ArgumentNullException("result"); + } + + int columns = Math.Min(MaxCsvColumns, GetMaxColumns(result)); + var builder = new StringBuilder(); + AppendCsvHeader(builder, result, columns); + + if (result.Rows.Count == 0) + { + AppendCsvRow(builder, result, null, columns); + } + else + { + foreach (ListRowResult row in result.Rows) + { + AppendCsvRow(builder, result, row, columns); + } + } + + return builder.ToString(); + } + + public void ExportCsv(ListReadResult result, string filePath) + { + WriteText(filePath, SerializeCsv(result), new UTF8Encoding(true)); + } + + private static void AppendCsvHeader(StringBuilder builder, ListReadResult result, int columns) + { + var headers = new List + { + "__ReadAtUtc", + "__Status", + "__Source", + "__ResultComplete", + "__RowsRead", + "__CellsRead", + "__ErrorCount", + "__Errors", + "__SelectedItems", + "__RowIndex", + "__RowId", + "__RowComplete", + "__RowError", + "__CellMetadata" + }; + + for (int columnIndex = 0; columnIndex < columns; columnIndex++) + { + string name = columnIndex < result.ColumnNames.Count + ? result.ColumnNames[columnIndex] + : null; + headers.Add(string.IsNullOrEmpty(name) ? "Column" + columnIndex : name); + } + + for (int index = 0; index < headers.Count; index++) + { + if (index > 0) + { + builder.Append(','); + } + builder.Append(EscapeCsv(headers[index])); + } + builder.AppendLine(); + } + + private static void AppendCsvRow(StringBuilder builder, ListReadResult result, ListRowResult row, int columns) + { + var fields = new List + { + result.ReadAtUtc.ToString("o", CultureInfo.InvariantCulture), + result.Status.ToString(), + result.Source.ToString(), + result.IsComplete.ToString(), + result.RowsRead.ToString(CultureInfo.InvariantCulture), + result.CellsRead.ToString(CultureInfo.InvariantCulture), + result.Errors.Count.ToString(CultureInfo.InvariantCulture), + BuildErrors(result), + BuildSelectedItems(result), + row == null ? string.Empty : row.RowIndex.ToString(CultureInfo.InvariantCulture), + row == null ? string.Empty : row.RowId, + row == null ? result.IsComplete.ToString() : row.IsComplete.ToString(), + row == null ? result.Error : row.Error, + row == null ? BuildErrors(result) : BuildCellMetadata(row) + }; + + for (int columnIndex = 0; columnIndex < columns; columnIndex++) + { + ListCellResult cell = row == null ? null : FindCell(row, columnIndex); + fields.Add(cell == null + ? string.Empty + : cell.ValueAvailable + ? cell.Value + : "[不可用] " + (cell.Error ?? "未暴露值")); + } + + for (int index = 0; index < fields.Count; index++) + { + if (index > 0) + { + builder.Append(','); + } + builder.Append(EscapeCsv(fields[index])); + } + builder.AppendLine(); + } + + private static int GetMaxColumns(ListReadResult result) + { + int max = result.ColumnNames.Count; + foreach (ListRowResult row in result.Rows) + { + foreach (ListCellResult cell in row.Cells) + { + if (cell.ColumnIndex >= 0) + { + max = Math.Max(max, cell.ColumnIndex + 1); + } + } + } + + return max; + } + + private static ListCellResult FindCell(ListRowResult row, int columnIndex) + { + foreach (ListCellResult cell in row.Cells) + { + if (cell.ColumnIndex == columnIndex) + { + return cell; + } + } + + return null; + } + + private static string BuildErrors(ListReadResult result) + { + var errors = new List(); + if (!string.IsNullOrEmpty(result.Error)) + { + errors.Add(result.Error); + } + errors.AddRange(result.Errors); + return string.Join(" | ", errors.ToArray()); + } + + private static string BuildSelectedItems(ListReadResult result) + { + var values = new List(); + foreach (ListSelectionResult item in result.SelectedItems) + { + values.Add(string.Format( + CultureInfo.InvariantCulture, + "{0}|{1}|{2}", + item.Index, + item.RowId, + item.Name)); + } + + return string.Join(";", values.ToArray()); + } + + private static string BuildCellMetadata(ListRowResult row) + { + var values = new List(); + foreach (ListCellResult cell in row.Cells) + { + values.Add(string.Format( + CultureInfo.InvariantCulture, + "{0}|{1}|{2}|{3}|{4}|{5}", + cell.ColumnIndex, + cell.ColumnId, + cell.ValueSource, + cell.ValueAvailable, + cell.IsAvailable, + cell.Error)); + } + + return string.Join(";", values.ToArray()); + } + + private static string EscapeCsv(string value) + { + if (value == null) + { + return string.Empty; + } + + // Prefix formula-like values so spreadsheet applications keep medical text literal. + if (value.Length > 0 && "=+-@".IndexOf(value[0]) >= 0) + { + 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)) + { + throw new ArgumentException("导出路径不能为空。", "filePath"); + } + + string fullPath = Path.GetFullPath(filePath); + string directory = Path.GetDirectoryName(fullPath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + File.WriteAllText(fullPath, content, encoding); + } + } +} diff --git a/src/pacs_win_uia/Services/MsaaService.cs b/src/pacs_win_uia/Services/MsaaService.cs new file mode 100644 index 0000000..e155b00 --- /dev/null +++ b/src/pacs_win_uia/Services/MsaaService.cs @@ -0,0 +1,561 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Runtime.InteropServices; +using Accessibility; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Interop; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// A child returned by an MSAA walk: either a simple child id or a COM child object. + internal sealed class MsaaChild + { + internal IAccessible Accessible; + internal object ChildId; + internal string PathKey; + internal bool IsObject; + + internal void Release() + { + if (Accessible != null) + { + try + { + Marshal.ReleaseComObject(Accessible); + } + catch (Exception) + { + // Releasing is best effort; a broken provider must not fail the read. + } + + Accessible = null; + } + } + } + + /// + /// 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 + { + private const int BatchSize = 128; + + /// + /// Root object for a window: OBJID_CLIENT first (the real content), falling back to + /// OBJID_WINDOW, which every HWND answers. + /// + public bool TryGetRoot(IntPtr hwnd, out object accessible, out string error) + { + accessible = null; + error = null; + if (hwnd == IntPtr.Zero) + { + error = "HWND 为空。"; + return false; + } + + string clientError; + if (TryGetObject(hwnd, MsaaNativeMethods.OBJID_CLIENT, out accessible, out clientError)) + { + return true; + } + + string windowError; + if (TryGetObject(hwnd, MsaaNativeMethods.OBJID_WINDOW, out accessible, out windowError)) + { + AppLog.Debug("MSAA:OBJID_CLIENT 不可用(" + clientError + "),已回退 OBJID_WINDOW。"); + return true; + } + + error = "OBJID_CLIENT 失败(" + clientError + ");OBJID_WINDOW 也失败(" + windowError + ")。"; + return false; + } + + private static bool TryGetObject(IntPtr hwnd, uint objectId, out object accessible, out string error) + { + accessible = null; + error = null; + try + { + Guid iid = MsaaNativeMethods.IID_IAccessible; + int hr = MsaaNativeMethods.AccessibleObjectFromWindow(hwnd, objectId, ref iid, out accessible); + if (hr != MsaaNativeMethods.S_OK) + { + error = FormatHResult(hr); + accessible = null; + return false; + } + + if (accessible == null) + { + error = "返回了空对象。"; + return false; + } + + return true; + } + catch (Exception ex) + { + error = ex.GetType().Name + ": " + ex.Message; + accessible = null; + return false; + } + } + + /// 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) + { + info = null; + windowHandle = IntPtr.Zero; + error = null; + IAccessible accessible = null; + try + { + var nativePoint = new NativeMethods.POINT(point.X, point.Y); + object accObject; + object childId; + int hr = MsaaNativeMethods.AccessibleObjectFromPoint(nativePoint, out accObject, out childId); + if (hr != MsaaNativeMethods.S_OK || accObject == null) + { + error = "AccessibleObjectFromPoint 失败:" + FormatHResult(hr); + return false; + } + + accessible = accObject as IAccessible; + if (accessible == null) + { + error = "返回的对象不是 IAccessible。"; + return false; + } + + if (childId is IAccessible) + { + // The leaf is the returned child object itself. + var childAccessible = (IAccessible)childId; + try + { + info = ReadSelf(childAccessible, MsaaNativeMethods.CHILDID_SELF, "point"); + TryReadWindow(childAccessible, info, out windowHandle); + return true; + } + finally + { + if (!ReferenceEquals(accessible, childAccessible)) + { + try + { + Marshal.ReleaseComObject(childAccessible); + } + catch (Exception) + { + // Best effort. + } + } + } + } + + object effectiveChildId = childId ?? MsaaNativeMethods.CHILDID_SELF; + info = ReadSelf(accessible, effectiveChildId, "point"); + TryReadWindow(accessible, info, out windowHandle); + if (info.Error == null && string.IsNullOrEmpty(info.Name) && info.RoleId < 0) + { + error = "该点没有可读取的 MSAA 对象。"; + return false; + } + + return true; + } + catch (Exception ex) + { + error = ex.GetType().Name + ": " + ex.Message; + return false; + } + finally + { + if (accessible != null) + { + try + { + Marshal.ReleaseComObject(accessible); + } + catch (Exception) + { + // Best effort. + } + } + } + } + + /// + /// 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 + /// window object): the window is first resolved by the Win32 descent, then asked what child + /// object or child id sits under the point. accHitTest takes screen coordinates. + /// + public bool TryHitTestInWindow(IntPtr handle, Point screenPoint, out MsaaNodeInfo info, out string error) + { + info = null; + error = null; + object accessibleObject; + if (!TryGetRoot(handle, out accessibleObject, out error)) + { + return false; + } + + var accessible = accessibleObject as IAccessible; + if (accessible == null) + { + error = "根对象不是 IAccessible。"; + return false; + } + + try + { + object hit; + try + { + hit = accessible.accHitTest(screenPoint.X, screenPoint.Y); + } + catch (Exception ex) + { + error = "accHitTest: " + FormatException(ex); + return false; + } + + string pathKey = "0x" + handle.ToInt64().ToString("X"); + if (hit is IAccessible) + { + var childAccessible = (IAccessible)hit; + try + { + info = ReadSelf(childAccessible, MsaaNativeMethods.CHILDID_SELF, pathKey + "/hit"); + IntPtr childWindow; + TryReadWindow(childAccessible, info, out childWindow); + return true; + } + finally + { + // A provider may answer accHitTest with the very same object; releasing the + // same RCW twice drops the COM object while it is still in use. + if (!ReferenceEquals(accessible, childAccessible)) + { + try + { + Marshal.ReleaseComObject(childAccessible); + } + catch (Exception) + { + // Best effort. + } + } + } + } + + int childId = MsaaConstants.ToInt(hit, -1); + if (childId < 0) + { + error = "accHitTest 没有返回子对象或子 ID。"; + return false; + } + + if (childId == MsaaNativeMethods.CHILDID_SELF) + { + // The window's own client object is the answer at this point. + info = ReadSelf(accessible, MsaaNativeMethods.CHILDID_SELF, pathKey); + return true; + } + + info = ReadSelf(accessible, childId, pathKey + "/hit" + childId); + return true; + } + finally + { + try + { + Marshal.ReleaseComObject(accessible); + } + catch (Exception) + { + // Best effort: every value was already snapshotted. + } + } + } + + /// Snapshot of one node (the object itself, or a simple child id read through it). + public MsaaNodeInfo ReadSelf(IAccessible accessible, object childId, string pathKey) + { + var info = new MsaaNodeInfo + { + PathKey = pathKey, + ChildId = childId is int ? (int)childId : MsaaNativeMethods.CHILDID_SELF + }; + + var errors = new List(); + info.Name = TryRead(delegate { return accessible.get_accName(childId); }, errors, "accName"); + info.Value = TryRead(delegate { return accessible.get_accValue(childId); }, errors, "accValue"); + info.Description = TryRead(delegate { return accessible.get_accDescription(childId); }, errors, "accDescription"); + info.DefaultAction = TryRead(delegate { return accessible.get_accDefaultAction(childId); }, errors, "accDefaultAction"); + + object role = TryReadObject(delegate { return accessible.get_accRole(childId); }, errors, "accRole"); + info.RoleId = MsaaConstants.ToInt(role, -1); + info.RoleText = MsaaConstants.DescribeRole(role); + + object state = TryReadObject(delegate { return accessible.get_accState(childId); }, errors, "accState"); + info.StateText = MsaaConstants.DescribeState(state); + + info.Location = TryReadLocation(accessible, childId, errors); + + if (errors.Count > 0) + { + info.Error = string.Join(";", errors.ToArray()); + } + + return info; + } + + /// + /// 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. + /// + internal IList ReadChildren( + IAccessible accessible, + object childId, + string pathKey, + int maxChildren, + out bool complete, + out string error) + { + complete = true; + error = null; + var children = new List(); + if (accessible == null || (childId is int && (int)childId != MsaaNativeMethods.CHILDID_SELF)) + { + // Simple child ids are leaves: they have no children of their own. + return children; + } + + int count; + try + { + count = accessible.accChildCount; + } + catch (Exception ex) + { + complete = false; + error = "accChildCount: " + FormatException(ex); + return children; + } + + if (count <= 0) + { + return children; + } + + int limit = maxChildren > 0 ? Math.Min(count, maxChildren) : count; + if (limit < count) + { + complete = false; + error = "子元素数 " + count + " 超过上限 " + maxChildren + ",已截断。"; + } + + for (int start = 0; start < limit; start += BatchSize) + { + int take = Math.Min(BatchSize, limit - start); + var buffer = new object[take]; + int obtained; + int hr; + try + { + hr = MsaaNativeMethods.AccessibleChildren(accessible, start, take, buffer, out obtained); + } + catch (Exception ex) + { + // Fall back to indexed accChild if the batched call is rejected. + obtained = 0; + hr = -1; + AppLog.Warn("MSAA:AccessibleChildren 批量读取失败(" + FormatException(ex) + "),回退逐项读取。"); + } + + if (hr != MsaaNativeMethods.S_OK || obtained <= 0) + { + for (int index = 0; index < take; index++) + { + MsaaChild single = ReadSingleChild(accessible, start + index, pathKey); + if (single != null) + { + children.Add(single); + } + else + { + complete = false; + if (string.IsNullOrEmpty(error)) + { + error = "AccessibleChildren 与 accChild 都无法读取子元素。"; + } + + break; + } + } + + continue; + } + + for (int index = 0; index < obtained; index++) + { + object item = buffer[index]; + if (item == null) + { + continue; + } + + var childObject = item as IAccessible; + if (childObject != null) + { + children.Add(new MsaaChild + { + Accessible = childObject, + ChildId = MsaaNativeMethods.CHILDID_SELF, + PathKey = pathKey + "/o" + (start + index), + IsObject = true + }); + continue; + } + + int id = MsaaConstants.ToInt(item, int.MinValue); + if (id == int.MinValue) + { + continue; + } + + children.Add(new MsaaChild + { + Accessible = null, + ChildId = id, + PathKey = pathKey + "/i" + id, + IsObject = false + }); + } + } + + return children; + } + + private static MsaaChild ReadSingleChild(IAccessible accessible, int index, string pathKey) + { + try + { + object child = accessible.get_accChild(index + 1); + if (child is IAccessible) + { + return new MsaaChild + { + Accessible = (IAccessible)child, + ChildId = MsaaNativeMethods.CHILDID_SELF, + PathKey = pathKey + "/o" + index, + IsObject = true + }; + } + + return new MsaaChild + { + Accessible = null, + ChildId = index + 1, + PathKey = pathKey + "/i" + (index + 1), + IsObject = false + }; + } + catch (Exception ex) + { + AppLog.Debug("MSAA:accChild(" + (index + 1) + ") 失败:" + FormatException(ex)); + return null; + } + } + + private static void TryReadWindow(IAccessible accessible, MsaaNodeInfo info, out IntPtr windowHandle) + { + windowHandle = IntPtr.Zero; + try + { + IntPtr hwnd; + if (MsaaNativeMethods.WindowFromAccessibleObject(accessible, out hwnd) == MsaaNativeMethods.S_OK && + hwnd != IntPtr.Zero) + { + windowHandle = hwnd; + info.HasWindow = true; + info.WindowHandle = hwnd.ToInt64(); + } + } + catch (Exception ex) + { + AppLog.Debug("MSAA:WindowFromAccessibleObject 失败:" + FormatException(ex)); + } + } + + private static string TryRead(Func getter, ICollection errors, string name) + { + try + { + return getter(); + } + catch (Exception ex) + { + errors.Add(name + ": " + FormatException(ex)); + return null; + } + } + + private static object TryReadObject(Func getter, ICollection errors, string name) + { + try + { + return getter(); + } + catch (Exception ex) + { + errors.Add(name + ": " + FormatException(ex)); + return null; + } + } + + private static NativeRectangleInfo TryReadLocation(IAccessible accessible, object childId, ICollection errors) + { + try + { + int left; + int top; + int width; + int height; + accessible.accLocation(out left, out top, out width, out height, childId); + if (width <= 0 || height <= 0) + { + return new NativeRectangleInfo(); + } + + return new NativeRectangleInfo(left, top, left + width, top + height); + } + catch (Exception ex) + { + errors.Add("accLocation: " + FormatException(ex)); + return new NativeRectangleInfo(); + } + } + + private static string FormatHResult(int hr) + { + return "HRESULT 0x" + ((uint)hr).ToString("X8"); + } + + private static string FormatException(Exception exception) + { + if (exception is COMException) + { + return string.Format("COM 0x{0:X8}: {1}", exception.HResult, exception.Message); + } + + return exception.GetType().Name + ": " + exception.Message; + } + } +} diff --git a/src/pacs_win_uia/Services/MsaaTreeReader.cs b/src/pacs_win_uia/Services/MsaaTreeReader.cs new file mode 100644 index 0000000..89c31fd --- /dev/null +++ b/src/pacs_win_uia/Services/MsaaTreeReader.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading; +using Accessibility; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Interop; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// MSAA tree reader. Every IAccessible is released as soon as its node has been snapshotted, and + /// only primitive values are kept — holding COM objects across a long walk keeps the target's + /// objects alive and is a leak. + /// + public sealed class MsaaTreeReader + { + private readonly MsaaService _msaa; + + public MsaaTreeReader() + : this(new MsaaService()) + { + } + + public MsaaTreeReader(MsaaService msaa) + { + _msaa = msaa ?? throw new ArgumentNullException("msaa"); + } + + public ControlTreeNode Read(IntPtr rootHandle, ControlTreeOptions options, CancellationToken cancellationToken) + { + if (options == null) + { + options = new ControlTreeOptions(); + } + + var root = new ControlTreeNode { Source = ControlTreeSource.Msaa }; + object accessibleObject; + string error; + if (!_msaa.TryGetRoot(rootHandle, out accessibleObject, out error)) + { + root.Msaa = new MsaaNodeInfo { Error = error }; + root.ChildrenComplete = false; + root.ChildrenError = error; + AppLog.Warn("MSAA 树:无法获取根对象(" + error + ")。"); + return root; + } + + var budget = new ReadBudget(options.MaxDepth, options.MaxNodes, options.Timeout, cancellationToken); + string pathKey = "0x" + rootHandle.ToInt64().ToString("X"); + IAccessible accessible = accessibleObject as IAccessible; + try + { + if (accessible == null) + { + root.Msaa = new MsaaNodeInfo { Error = "根对象不是 IAccessible。" }; + root.ChildrenComplete = false; + root.ChildrenError = "根对象不是 IAccessible。"; + return root; + } + + root.Msaa = _msaa.ReadSelf(accessible, MsaaNativeMethods.CHILDID_SELF, pathKey); + BuildChildren(accessible, MsaaNativeMethods.CHILDID_SELF, pathKey, root, options, budget, 0); + } + catch (TimeoutException ex) + { + root.ChildrenComplete = false; + root.ChildrenError = ex.Message; + } + catch (OperationCanceledException) + { + root.ChildrenComplete = false; + root.ChildrenError = "Canceled"; + } + catch (Exception ex) + { + root.ChildrenComplete = false; + root.ChildrenError = ex.GetType().Name + ": " + ex.Message; + AppLog.Error("MSAA 树读取失败。", ex); + } + finally + { + if (accessible != null) + { + try + { + Marshal.ReleaseComObject(accessible); + } + catch (Exception) + { + // Best effort: a provider that refuses release must not fail the read. + } + } + } + + return root; + } + + private void BuildChildren( + IAccessible parent, + object parentChildId, + string parentPath, + ControlTreeNode parentNode, + ControlTreeOptions options, + ReadBudget budget, + int depth) + { + budget.ThrowIfStopped(); + bool complete; + string error; + IList children = _msaa.ReadChildren( + parent, parentChildId, parentPath, options.MaxMsaaChildrenPerNode, out complete, out error); + parentNode.ChildrenComplete = complete; + parentNode.ChildrenError = error; + + foreach (MsaaChild child in children) + { + try + { + budget.ThrowIfStopped(); + budget.CountNode(); + } + catch (TimeoutException) + { + parentNode.ChildrenComplete = false; + parentNode.ChildrenError = "达到超时或节点上限,结果不完整。"; + child.Release(); + return; + } + catch (OperationCanceledException) + { + parentNode.ChildrenComplete = false; + parentNode.ChildrenError = "Canceled"; + child.Release(); + return; + } + + try + { + var node = new ControlTreeNode { Source = ControlTreeSource.Msaa }; + if (child.IsObject && child.Accessible != null) + { + node.Msaa = _msaa.ReadSelf(child.Accessible, MsaaNativeMethods.CHILDID_SELF, child.PathKey); + parentNode.Children.Add(node); + + // A simple child id has no children of its own; a COM child object may. + if (depth + 1 < budget.MaxDepth) + { + BuildChildren(child.Accessible, MsaaNativeMethods.CHILDID_SELF, child.PathKey, node, options, budget, depth + 1); + } + else + { + node.ChildrenComplete = false; + node.ChildrenError = "MaxDepthReached"; + } + } + else + { + // Read through the parent with the child id. + node.Msaa = _msaa.ReadSelf(parent, child.ChildId, child.PathKey); + parentNode.Children.Add(node); + } + } + finally + { + child.Release(); + } + } + } + } +} diff --git a/src/pacs_win_uia/Services/NativeWindowService.cs b/src/pacs_win_uia/Services/NativeWindowService.cs new file mode 100644 index 0000000..c171371 --- /dev/null +++ b/src/pacs_win_uia/Services/NativeWindowService.cs @@ -0,0 +1,342 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Text; +using pacs_win_uia.Interop; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// Read-only Win32 window discovery and snapshot service. + /// + public sealed class NativeWindowService + { + /// Budget for reading a window title across processes. + private const uint TitleReadTimeoutMs = 200; + + private readonly int _excludedProcessId; + + public NativeWindowService() + : this(Process.GetCurrentProcess().Id) + { + } + + public NativeWindowService(int excludedProcessId) + { + _excludedProcessId = excludedProcessId; + } + + public IList EnumerateTopLevelWindows(bool includeHidden) + { + return EnumerateTopLevelWindowsResult(includeHidden).Windows; + } + + public WindowEnumerationResult EnumerateTopLevelWindowsResult(bool includeHidden) + { + var handles = new List(); + bool success = NativeMethods.EnumWindows( + delegate(IntPtr hWnd, IntPtr lParam) + { + handles.Add(hWnd); + return true; + }, + IntPtr.Zero); + + var result = new WindowEnumerationResult + { + Succeeded = success + }; + // Process.GetProcessById is slow; one lookup per distinct PID keeps a long window + // list from blocking the UI thread on every refresh. + var processNameCache = new Dictionary(); + foreach (IntPtr handle in handles) + { + NativeWindowInfo snapshot = Capture(handle, processNameCache); + if (snapshot == null || snapshot.Handle == IntPtr.Zero) + { + continue; + } + + if (!includeHidden && !snapshot.IsVisible) + { + continue; + } + + if (snapshot.ProcessId == _excludedProcessId) + { + continue; + } + + result.Windows.Add(snapshot); + } + + if (!success) + { + result.Error = "EnumWindows 失败,Win32 错误码: " + Marshal.GetLastWin32Error(); + } + + return result; + } + + public NativeWindowInfo Capture(IntPtr handle) + { + return Capture(handle, null); + } + + private NativeWindowInfo Capture(IntPtr handle, IDictionary processNameCache) + { + if (handle == IntPtr.Zero || !NativeMethods.IsWindow(handle)) + { + return null; + } + + var result = new NativeWindowInfo(handle); + var errors = new List(); + try + { + uint processId; + if (NativeMethods.GetWindowThreadProcessId(handle, out processId) == 0) + { + errors.Add("进程 ID: GetWindowThreadProcessId 返回失败。"); + } + + result.ProcessId = unchecked((int)processId); + result.ProcessName = TryGetProcessName(result.ProcessId, errors, processNameCache); + result.Title = ReadWindowText(handle, errors); + result.ClassName = ReadClassName(handle, errors); + result.ParentHwndHex = NativeWindowInfo.FormatHandle( + NativeMethods.GetAncestor(handle, NativeMethods.GA_PARENT)); + result.RootHwndHex = NativeWindowInfo.FormatHandle( + NativeMethods.GetAncestor(handle, NativeMethods.GA_ROOT)); + result.IsVisible = NativeMethods.IsWindowVisible(handle); + result.IsMinimized = NativeMethods.IsIconic(handle); + result.WindowBounds = ReadWindowRectangle(handle, errors); + result.ClientBounds = ReadClientRectangle(handle, errors); + result.IsOwnProcess = result.ProcessId == _excludedProcessId; + } + catch (Exception ex) + { + errors.Add(ex.GetType().Name + ": " + ex.Message); + } + + result.Error = errors.Count == 0 ? null : string.Join(" | ", errors.ToArray()); + return result; + } + + public NativeWindowInfo FindWindowAt(Point screenPoint) + { + IntPtr handle = NativeMethods.WindowFromPoint(screenPoint); + if (handle == IntPtr.Zero) + { + return null; + } + + NativeWindowInfo result = Capture(handle); + return IsExcludedProcess(result) ? null : result; + } + + public NativeWindowInfo FindWindowAt(Point screenPoint, params IntPtr[] ignoredHandles) + { + IntPtr handle = NativeMethods.WindowFromPoint(screenPoint); + for (int index = 0; handle != IntPtr.Zero && ContainsHandle(ignoredHandles, handle); index++) + { + IntPtr parent = NativeMethods.GetAncestor(handle, NativeMethods.GA_PARENT); + if (parent == IntPtr.Zero || parent == handle) + { + break; + } + + handle = parent; + } + + if (handle == IntPtr.Zero) + { + return null; + } + + NativeWindowInfo result = Capture(handle); + return IsExcludedProcess(result) ? null : result; + } + + private static bool ContainsHandle(IntPtr[] handles, IntPtr value) + { + if (handles == null) + { + return false; + } + + foreach (IntPtr handle in handles) + { + if (handle == value) + { + return true; + } + } + + return false; + } + + public bool IsExcludedProcess(NativeWindowInfo window) + { + return window != null && window.ProcessId == _excludedProcessId; + } + + private static NativeWindowInfo CreateEnumerationFailure(string error) + { + var result = new NativeWindowInfo(IntPtr.Zero) + { + Error = error + }; + return result; + } + + /// + /// GetWindowText sends WM_GETTEXT into the target process and blocks forever on a hung + /// window, and RefreshWindows runs on the UI thread — so the title goes through + /// SendMessageTimeout with SMTO_ABORTIFHUNG instead. + /// + private static string ReadWindowText(IntPtr handle, ICollection errors) + { + try + { + int length = NativeMethods.GetWindowTextLength(handle); + if (length <= 0) + { + return string.Empty; + } + + var builder = new StringBuilder(Math.Min(Math.Max(length + 1, 256), 1024)); + IntPtr messageResult; + IntPtr sent = NativeMethods.SendMessageTimeout( + handle, + NativeMethods.WM_GETTEXT, + new IntPtr(builder.Capacity), + builder, + NativeMethods.SMTO_ABORTIFHUNG, + TitleReadTimeoutMs, + out messageResult); + if (sent == IntPtr.Zero) + { + errors.Add("窗口标题: 目标无响应(已超时 " + TitleReadTimeoutMs + " ms)。"); + return string.Empty; + } + + return builder.ToString(); + } + catch (Exception ex) + { + errors.Add("窗口标题: " + ex.Message); + return null; + } + } + + private static string ReadClassName(IntPtr handle, ICollection errors) + { + try + { + var builder = new StringBuilder(256); + NativeMethods.GetClassName(handle, builder, builder.Capacity); + return builder.ToString(); + } + catch (Exception ex) + { + errors.Add("窗口类名: " + ex.Message); + return null; + } + } + + private static NativeRectangleInfo ReadWindowRectangle(IntPtr handle, ICollection errors) + { + try + { + NativeMethods.RECT rect; + if (NativeMethods.GetWindowRect(handle, out rect)) + { + return new NativeRectangleInfo(rect.Left, rect.Top, rect.Right, rect.Bottom); + } + + errors.Add("窗口矩形: Win32 API 返回失败。"); + } + catch (Exception ex) + { + errors.Add("窗口矩形: " + ex.Message); + } + + return new NativeRectangleInfo(); + } + + private static NativeRectangleInfo ReadClientRectangle(IntPtr handle, ICollection errors) + { + try + { + NativeMethods.RECT rect; + if (!NativeMethods.GetClientRect(handle, out rect)) + { + errors.Add("客户区矩形: GetClientRect 返回失败。"); + return new NativeRectangleInfo(); + } + + var topLeft = new NativeMethods.POINT(rect.Left, rect.Top); + var bottomRight = new NativeMethods.POINT(rect.Right, rect.Bottom); + if (!NativeMethods.ClientToScreen(handle, ref topLeft) || + !NativeMethods.ClientToScreen(handle, ref bottomRight)) + { + errors.Add("客户区矩形: ClientToScreen 返回失败。"); + return new NativeRectangleInfo(); + } + + return new NativeRectangleInfo( + topLeft.X, + topLeft.Y, + bottomRight.X, + bottomRight.Y); + } + catch (Exception ex) + { + errors.Add("客户区矩形: " + ex.Message); + return new NativeRectangleInfo(); + } + } + + internal static string TryGetProcessName( + int processId, + ICollection errors, + IDictionary processNameCache) + { + if (processId <= 0) + { + return null; + } + + string cached; + if (processNameCache != null && processNameCache.TryGetValue(processId, out cached)) + { + return cached; + } + + string name; + try + { + using (Process process = Process.GetProcessById(processId)) + { + name = process.ProcessName; + } + } + catch (Exception ex) + { + errors.Add("进程名: " + ex.GetType().Name); + name = null; + } + + if (processNameCache != null && name != null) + { + processNameCache[processId] = name; + } + + return name; + } + } +} diff --git a/src/pacs_win_uia/Services/ReadBudget.cs b/src/pacs_win_uia/Services/ReadBudget.cs new file mode 100644 index 0000000..db8eee1 --- /dev/null +++ b/src/pacs_win_uia/Services/ReadBudget.cs @@ -0,0 +1,75 @@ +using System; +using System.Threading; + +namespace pacs_win_uia.Services +{ + /// + /// The shared bound for every tree reader (UIA / MSAA / Win32): depth, node count, deadline and + /// cancellation. A synchronous cross-process provider call cannot be interrupted, so the deadline + /// is only enforceable between calls — it bounds how much more work may be started, not one call. + /// + public sealed class ReadBudget + { + private int _nodeCount; + + public ReadBudget(int maxDepth, int maxNodes, TimeSpan timeout, CancellationToken cancellationToken) + { + if (maxDepth < 0) + { + throw new ArgumentOutOfRangeException("maxDepth"); + } + + if (maxNodes < 1) + { + throw new ArgumentOutOfRangeException("maxNodes"); + } + + MaxDepth = maxDepth; + MaxNodes = maxNodes; + Deadline = timeout == Timeout.InfiniteTimeSpan + ? DateTime.MaxValue + : timeout <= TimeSpan.Zero + ? DateTime.UtcNow + : DateTime.UtcNow.Add(timeout); + CancellationToken = cancellationToken; + _nodeCount = 1; + } + + public int MaxDepth { get; private set; } + + public int MaxNodes { get; private set; } + + public int NodeCount + { + get { return _nodeCount; } + } + + 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(); + if (DateTime.UtcNow > Deadline) + { + throw new TimeoutException("控件树读取超时。"); + } + } + } +} diff --git a/src/pacs_win_uia/Services/TargetProbeService.cs b/src/pacs_win_uia/Services/TargetProbeService.cs new file mode 100644 index 0000000..1e655f8 --- /dev/null +++ b/src/pacs_win_uia/Services/TargetProbeService.cs @@ -0,0 +1,311 @@ +using System; +using System.Drawing; +using System.Threading; +using System.Threading.Tasks; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Interop; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// Combines the Win32, UIA and MSAA point probes into one read-only result. Order matters: + /// Win32 is a local call that cannot hang, so it always provides a target; UIA and MSAA then add + /// detail where the target exposes it. + /// + public sealed class TargetProbeService + { + private const int MaxDescendDepth = 16; + + private readonly NativeWindowService _windowService; + private readonly UiAutomationService _uiAutomationService; + private readonly MsaaService _msaaService; + private readonly int _ownProcessId; + + public TargetProbeService( + NativeWindowService windowService, + UiAutomationService uiAutomationService, + int ownProcessId) + : this(windowService, uiAutomationService, new MsaaService(), ownProcessId) + { + } + + public TargetProbeService( + NativeWindowService windowService, + UiAutomationService uiAutomationService, + MsaaService msaaService, + int ownProcessId) + { + _windowService = windowService ?? throw new ArgumentNullException("windowService"); + _uiAutomationService = uiAutomationService ?? throw new ArgumentNullException("uiAutomationService"); + _msaaService = msaaService ?? throw new ArgumentNullException("msaaService"); + _ownProcessId = ownProcessId; + } + + public PointPickResult Probe(Point screenPoint) + { + return Probe(screenPoint, IntPtr.Zero); + } + + public PointPickResult Probe(Point screenPoint, IntPtr knownWindowHandle) + { + var result = new PointPickResult { ScreenPoint = screenPoint }; + + // --- Win32: instantaneous, and the only source that cannot block --------------- + IntPtr handle = knownWindowHandle == IntPtr.Zero + ? NativeMethods.WindowFromPoint(screenPoint) + : knownWindowHandle; + IntPtr deepestHandle = DescendToDeepestChild(handle, screenPoint); + NativeWindowInfo deepest = _windowService.Capture(deepestHandle) ?? _windowService.Capture(handle); + if (deepest == null) + { + result.FailureReason = "屏幕坐标下没有可访问的窗口,或命中了本工具窗口。"; + return result; + } + + result.Window = deepest; + result.DeepestWindow = deepest; + result.IsToolWindow = deepest.ProcessId == _ownProcessId || deepest.IsOwnProcess; + if (result.IsToolWindow) + { + result.FailureReason = "命中本工具窗口,已排除。"; + return result; + } + + result.PickSource = ControlTreeSource.Win32; + result.Bounds = deepest.WindowBounds; + AppLog.Debug("拾取:Win32 层完成,最深层=" + NativeWindowInfo.FormatHandle(deepestHandle) + + ",矩形=" + (result.Bounds == null ? "(无)" : result.Bounds.ToString())); + + // --- UIA: walked down from the window the cursor is over ---------------------- + result.AutomationElement = knownWindowHandle == IntPtr.Zero + ? _uiAutomationService.FromPoint(screenPoint) + : _uiAutomationService.FromHandleAtPoint(handle, screenPoint); + + bool uiaMatchesWindow = result.AutomationElement != null && result.AutomationElement.IsAvailable && + (result.AutomationElement.ProcessId <= 0 || result.AutomationElement.ProcessId == deepest.ProcessId); + if (result.AutomationElement != null && result.AutomationElement.IsAvailable && !uiaMatchesWindow) + { + result.FailureReason = "UIA 元素与 Win32 窗口属于不同进程,已拒绝合并为同一目标。"; + result.AutomationElement.IsAvailable = false; + } + + AppLog.Debug("拾取:UIA 层完成,元素=" + (result.AutomationElement == null ? "(无)" : result.AutomationElement.ToString())); + bool uiaUsable = result.AutomationElement != null && result.AutomationElement.IsAvailable; + // UIA answering with a plain Window means it exposed nothing under the cursor. That is + // the common case for browser shells and Explorer, and it must NOT end the search: the + // highlight would cover the whole window instead of the control under the pointer. + bool uiaIsWindowOnly = uiaUsable && + string.Equals(result.AutomationElement.ControlType, "ControlType.Window", StringComparison.Ordinal); + if (uiaUsable) + { + result.PickSource = ControlTreeSource.Uia; + UseIfSmaller(result, result.AutomationElement.BoundingRectangle); + } + + if (!uiaUsable || uiaIsWindowOnly) + { + // --- MSAA: hit-tested on the deepest window Win32 already resolved ----------- + AppLog.Debug("拾取:进入 MSAA 命中测试(uiaUsable=" + uiaUsable + ",windowOnly=" + uiaIsWindowOnly + ")。"); + TryMsaaHitTest(screenPoint, result); + AppLog.Debug("拾取:MSAA 命中测试返回。"); + } + + bool msaaUsable = result.Msaa != null && result.Msaa.Location != null && result.Msaa.Location.IsValid; + if (!uiaUsable || uiaIsWindowOnly) + { + result.IsWindowOnlyPick = !msaaUsable; + } + + if (!result.HasAutomationElement && !msaaUsable) + { + result.FailureReason = result.FailureReason ?? + (result.AutomationElement == null + ? "UIA 未返回元素,MSAA 也未命中;已保留 Win32 窗口信息。" + : result.AutomationElement.Error ?? "UIA 元素不可访问,MSAA 也未命中;已保留 Win32 窗口信息。"); + } + + if (result.IsWindowOnlyPick) + { + AppLog.Warn("拾取:光标下只能确定到窗口「" + deepest + "」。" + + "UIA 返回的是窗口本身,MSAA 在该窗口上也没有命中内部对象;" + + "目标可能是单 HWND 自绘界面或未开启无障碍。"); + } + + return result; + } + + /// + /// 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) + { + return; + } + + if (result.Bounds == null || !result.Bounds.IsValid) + { + result.Bounds = candidate; + return; + } + + long currentArea = (long)result.Bounds.Width * result.Bounds.Height; + long candidateArea = (long)candidate.Width * candidate.Height; + if (candidateArea > 0 && candidateArea < currentArea) + { + result.Bounds = candidate; + } + } + + private void TryMsaaHitTest(Point screenPoint, PointPickResult result) + { + try + { + MsaaNodeInfo info = null; + IntPtr msaaWindow = IntPtr.Zero; + string error = null; + + // Hit-test on the deepest window Win32 already found: that object knows its own + // children, which the global point query usually does not. + IntPtr deepest = result.DeepestWindow == null ? IntPtr.Zero : result.DeepestWindow.Handle; + bool hit = deepest != IntPtr.Zero && + _msaaService.TryHitTestInWindow(deepest, screenPoint, out info, out error); + if (!hit) + { + AppLog.Debug("拾取:在深层窗口 " + NativeWindowInfo.FormatHandle(deepest) + + " 上 accHitTest 未命中(" + error + "),改用全局 AccessibleObjectFromPoint。"); + if (!_msaaService.TryHitTest(screenPoint, out info, out msaaWindow, out error)) + { + AppLog.Debug("拾取:MSAA 未命中(" + error + ")。"); + return; + } + } + + if (msaaWindow != IntPtr.Zero) + { + uint processId; + NativeMethods.GetWindowThreadProcessId(msaaWindow, out processId); + int msaaProcessId = unchecked((int)processId); + if (msaaProcessId > 0 && msaaProcessId != result.Window.ProcessId) + { + AppLog.Warn("拾取:MSAA 对象属于进程 " + msaaProcessId + + ",与 Win32 窗口进程 " + result.Window.ProcessId + " 不同,已拒绝合并。"); + return; + } + } + + result.Msaa = info; + if (result.PickSource != ControlTreeSource.Uia) + { + result.PickSource = ControlTreeSource.Msaa; + } + + // MSAA hit-tests resolve to a child id/cell, so this is usually the tightest rect. + UseIfSmaller(result, info.Location); + } + catch (Exception ex) + { + AppLog.Warn("拾取:MSAA 命中测试异常:" + ex.GetType().Name + ": " + ex.Message); + } + } + + /// + /// Win32-only resolution of a screen point: no UIA/MSAA call, so it always returns quickly. + /// Used when a UIA probe does not come back in time (an unresponsive provider must not be + /// able to keep the picker open forever). + /// + public PointPickResult ProbeWindowOnly(Point screenPoint, IntPtr knownWindowHandle) + { + var result = new PointPickResult { ScreenPoint = screenPoint }; + NativeWindowInfo window = knownWindowHandle == IntPtr.Zero + ? _windowService.Capture(DescendToDeepestChild(NativeMethods.WindowFromPoint(screenPoint), screenPoint)) + : _windowService.Capture(knownWindowHandle); + if (window == null) + { + result.FailureReason = "屏幕坐标下没有可访问的窗口,或命中了本工具窗口。"; + return result; + } + + result.Window = window; + result.DeepestWindow = window; + result.Bounds = window.WindowBounds; + result.PickSource = ControlTreeSource.Win32; + result.IsToolWindow = window.ProcessId == _ownProcessId || window.IsOwnProcess; + if (result.IsToolWindow) + { + result.FailureReason = "命中本工具窗口,已排除。"; + return result; + } + + result.FailureReason = "UIA 元素探测未在限定时间内返回(目标可能无响应);已按 Win32 窗口信息确认目标。"; + return result; + } + + /// + /// Walks down the child-window chain to the deepest window containing the point. The renderer + /// window of a browser shell is a real child HWND, so this is how Win32 gets inside one. + /// ChildWindowFromPointEx takes coordinates relative to the parent's client area, so the point + /// is converted at every level. + /// + private static IntPtr DescendToDeepestChild(IntPtr handle, Point screenPoint) + { + IntPtr current = handle; + var chain = new System.Text.StringBuilder(); + for (int depth = 0; depth < MaxDescendDepth && current != IntPtr.Zero; depth++) + { + var clientPoint = new NativeMethods.POINT(screenPoint.X, screenPoint.Y); + if (!NativeMethods.ScreenToClient(current, ref clientPoint)) + { + break; + } + + // WS_EX_TRANSPARENT children (DirectUIHWND and friends) are still the real content + // host, so only invisible children are skipped. + IntPtr child = NativeMethods.ChildWindowFromPointEx( + current, + new Point(clientPoint.X, clientPoint.Y), + NativeMethods.CWP_SKIPINVISIBLE); + if (child == IntPtr.Zero || child == current) + { + break; + } + + current = child; + if (chain.Length > 0) + { + chain.Append(" > "); + } + + chain.Append(NativeWindowInfo.FormatHandle(current)); + } + + if (chain.Length > 0) + { + AppLog.Info("拾取下钻:从 " + NativeWindowInfo.FormatHandle(handle) + " 到最深层 " + chain); + } + + return current; + } + + public Task ProbeAsync( + Point screenPoint, + CancellationToken cancellationToken, + IntPtr knownWindowHandle = default(IntPtr)) + { + // A synchronous provider call cannot be interrupted; on a pool thread a wedged provider + // would permanently consume pool capacity, so this runs on its own thread. + return Task.Factory.StartNew( + delegate + { + cancellationToken.ThrowIfCancellationRequested(); + return Probe(screenPoint, knownWindowHandle); + }, + cancellationToken, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + } + } +} diff --git a/src/pacs_win_uia/Services/UiAutomationService.cs b/src/pacs_win_uia/Services/UiAutomationService.cs new file mode 100644 index 0000000..6b04835 --- /dev/null +++ b/src/pacs_win_uia/Services/UiAutomationService.cs @@ -0,0 +1,885 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; +using System.Windows.Automation; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// Converts live UI Automation objects into short-lived, serializable snapshots. + /// No pattern action is invoked by this service. + /// + public sealed class UiAutomationService + { + private static readonly PatternDescriptor[] KnownPatterns = + { + new PatternDescriptor("ValuePattern", ValuePattern.Pattern), + new PatternDescriptor("TextPattern", TextPattern.Pattern), + new PatternDescriptor("InvokePattern", InvokePattern.Pattern), + new PatternDescriptor("SelectionPattern", SelectionPattern.Pattern), + new PatternDescriptor("SelectionItemPattern", SelectionItemPattern.Pattern), + new PatternDescriptor("ExpandCollapsePattern", ExpandCollapsePattern.Pattern), + new PatternDescriptor("ScrollPattern", ScrollPattern.Pattern), + new PatternDescriptor("GridPattern", GridPattern.Pattern), + new PatternDescriptor("TablePattern", TablePattern.Pattern), + new PatternDescriptor("WindowPattern", WindowPattern.Pattern), + new PatternDescriptor("TransformPattern", TransformPattern.Pattern), + new PatternDescriptor("ScrollItemPattern", ScrollItemPattern.Pattern), + new PatternDescriptor("TogglePattern", TogglePattern.Pattern), + new PatternDescriptor("RangeValuePattern", RangeValuePattern.Pattern), + new PatternDescriptor("MultipleViewPattern", MultipleViewPattern.Pattern) + }; + + /// + /// 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 + /// (UWP/Qt/Chromium) takes seconds because every property read is a separate RPC. + /// + public static CacheRequest CreateSnapshotCache() + { + var request = new CacheRequest(); + request.Add(AutomationElement.NameProperty); + request.Add(AutomationElement.AutomationIdProperty); + request.Add(AutomationElement.ControlTypeProperty); + request.Add(AutomationElement.ClassNameProperty); + request.Add(AutomationElement.FrameworkIdProperty); + request.Add(AutomationElement.NativeWindowHandleProperty); + request.Add(AutomationElement.IsEnabledProperty); + request.Add(AutomationElement.IsOffscreenProperty); + request.Add(AutomationElement.ProcessIdProperty); + request.Add(AutomationElement.BoundingRectangleProperty); + request.Add(AutomationElement.HasKeyboardFocusProperty); + request.Add(AutomationElement.IsKeyboardFocusableProperty); + foreach (PatternDescriptor descriptor in KnownPatterns) + { + request.Add(descriptor.Pattern); + } + + return request; + } + + /// + /// 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). + /// + public UiaElementInfo InspectCached(AutomationElement element) + { + if (element == null) + { + return Failure("UIA 元素为空。"); + } + + try + { + AutomationElement.AutomationElementInformation cached = element.Cached; + var snapshot = new UiaElementInfo + { + Element = element, + Name = cached.Name, + AutomationId = cached.AutomationId, + ControlType = cached.ControlType == null ? null : cached.ControlType.ProgrammaticName, + ClassName = cached.ClassName, + FrameworkId = cached.FrameworkId, + NativeWindowHandle = cached.NativeWindowHandle, + IsEnabled = cached.IsEnabled, + IsOffscreen = cached.IsOffscreen, + ProcessId = cached.ProcessId, + BoundingRectangle = ToRectangleInfo(cached.BoundingRectangle), + HasKeyboardFocus = cached.HasKeyboardFocus, + IsKeyboardFocusable = cached.IsKeyboardFocusable, + IsAvailable = true + }; + + foreach (PatternDescriptor descriptor in KnownPatterns) + { + object ignored; + if (element.TryGetCachedPattern(descriptor.Pattern, out ignored)) + { + snapshot.SupportedPatterns.Add(descriptor.Name); + } + } + + // RuntimeId is a provider call that cannot be cached; it is filled on demand + // (see UiaElementInfo.EnsureRuntimeId) instead of once per tree node. + return snapshot; + } + catch (Exception ex) + { + AppLog.Debug("缓存快照不可用,回退实时读取:" + ex.GetType().Name + ": " + ex.Message); + return Inspect(element); + } + } + + public UiaElementInfo FromHandle(IntPtr handle) + { + if (handle == IntPtr.Zero) + { + return Failure("HWND 为空。"); + } + + try + { + return Inspect(AutomationElement.FromHandle(handle)); + } + catch (Exception ex) + { + return Failure(FormatException(ex)); + } + } + + /// + /// 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 + /// real tree from an inner window element rather than from the top-level one. + /// + public IntPtr FindNestedContentWindow(IntPtr handle) + { + if (handle == IntPtr.Zero) + { + return IntPtr.Zero; + } + + try + { + AutomationElement root = AutomationElement.FromHandle(handle); + if (root == null) + { + return IntPtr.Zero; + } + + var queue = new Queue>(); + queue.Enqueue(new KeyValuePair(root, 0)); + int visited = 0; + while (queue.Count > 0 && visited < 100) + { + KeyValuePair item = queue.Dequeue(); + visited++; + if (item.Value >= 3) + { + continue; + } + + AutomationElementCollection children = item.Key.FindAll(TreeScope.Children, Condition.TrueCondition); + foreach (AutomationElement child in children) + { + AutomationElement.AutomationElementInformation info = child.Current; + bool isWindow = info.ControlType == ControlType.Window && info.NativeWindowHandle != 0; + if (isWindow && IsContentHost(info)) + { + return new IntPtr(info.NativeWindowHandle); + } + + queue.Enqueue(new KeyValuePair(child, item.Value + 1)); + } + } + } + catch (Exception ex) + { + AppLog.Debug("查找内层内容窗口失败:" + ex.GetType().Name + ": " + ex.Message); + } + + return IntPtr.Zero; + } + + /// XAML / UIA providers only; a nested Win32 window is usually chrome, not content. + private static bool IsContentHost(AutomationElement.AutomationElementInformation info) + { + if (string.Equals(info.FrameworkId, "XAML", StringComparison.OrdinalIgnoreCase) || + string.Equals(info.FrameworkId, "UIA", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + string className = info.ClassName ?? string.Empty; + return className.IndexOf("CoreWindow", StringComparison.OrdinalIgnoreCase) >= 0 || + className.IndexOf("Chrome_RenderWidgetHost", StringComparison.OrdinalIgnoreCase) >= 0; + } + + public UiaElementInfo FromPoint(Point point) + { + try + { + return Inspect(AutomationElement.FromPoint(new System.Windows.Point(point.X, point.Y))); + } + catch (Exception ex) + { + return Failure(FormatException(ex)); + } + } + + public UiaElementInfo FromHandleAtPoint(IntPtr handle, Point point) + { + if (handle == IntPtr.Zero) + { + return Failure("HWND 为空。"); + } + + try + { + AutomationElement root = AutomationElement.FromHandle(handle); + var searchState = new PointProbeState(500); + AutomationElement deepest = FindDeepestElementAtPoint(root, point, 0, 8, searchState); + return Inspect(deepest ?? root); + } + catch (Exception ex) + { + return Failure(FormatException(ex)); + } + } + + private sealed class PointProbeState + { + internal PointProbeState(int maximumNodes) + { + Remaining = maximumNodes; + } + + internal int Remaining { get; private set; } + + internal bool Consume() + { + if (Remaining <= 0) + { + return false; + } + + Remaining--; + return true; + } + } + + private static AutomationElement FindDeepestElementAtPoint( + AutomationElement element, + Point point, + int depth, + int maxDepth, + PointProbeState state) + { + if (element == null || depth >= maxDepth || state.Remaining <= 0) + { + return element; + } + + AutomationElement best = element; + try + { + AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(element); + while (child != null && state.Consume()) + { + System.Windows.Rect bounds = child.Current.BoundingRectangle; + if (!bounds.IsEmpty && bounds.Contains(new System.Windows.Point(point.X, point.Y))) + { + best = FindDeepestElementAtPoint(child, point, depth + 1, maxDepth, state); + } + + child = TreeWalker.ControlViewWalker.GetNextSibling(child); + } + } + catch + { + // The root/last usable element remains a valid fallback when a provider rejects a child query. + } + + return best; + } + + /// + /// Compact structural description of an element and its ancestors, for console diagnostics. + /// Bounded, read-only and exception-safe: it only ever feeds the log. + /// + public IList DescribeChain(AutomationElement element, int maxAncestors, int maxChildren) + { + var lines = new List(); + AutomationElement current = element; + for (int level = 0; current != null && level <= maxAncestors; level++) + { + lines.Add(level + ": " + DescribeElement(current, maxChildren)); + try + { + current = TreeWalker.ControlViewWalker.GetParent(current); + } + catch (Exception ex) + { + lines.Add(" 向上查找中断:" + FormatException(ex)); + break; + } + } + + return lines; + } + + /// Compact description of an element's direct children, for console diagnostics. + public IList DescribeChildren(AutomationElement element, int maxChildren) + { + var lines = new List(); + if (element == null) + { + return lines; + } + + try + { + AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(element); + int index = 0; + while (child != null && index < maxChildren) + { + string description; + try + { + AutomationElement.AutomationElementInformation current = child.Current; + description = string.Format( + "{0} | Name=\"{1}\" | AutomationId=\"{2}\" | Class=\"{3}\" | HWND=0x{4:X} | Framework={5}", + current.ControlType == null ? "(未知类型)" : current.ControlType.ProgrammaticName, + current.Name, + current.AutomationId, + current.ClassName, + current.NativeWindowHandle, + current.FrameworkId); + } + catch (Exception ex) + { + description = "(子元素属性读取失败) " + FormatException(ex); + } + + lines.Add(" 子元素 " + index + ": " + description); + index++; + child = TreeWalker.ControlViewWalker.GetNextSibling(child); + } + + if (index == 0) + { + lines.Add(" 该元素没有暴露任何 ControlView 子元素。"); + } + } + catch (Exception ex) + { + lines.Add(" 子元素枚举失败:" + FormatException(ex)); + } + + return lines; + } + + private static string DescribeElement(AutomationElement element, int maxChildren) + { + string description; + try + { + AutomationElement.AutomationElementInformation current = element.Current; + description = string.Format( + "{0} | Name=\"{1}\" | AutomationId=\"{2}\" | Class=\"{3}\" | Framework=\"{4}\" | PID={5} | HWND=0x{6:X} | Offscreen={7}", + current.ControlType == null ? "(未知类型)" : current.ControlType.ProgrammaticName, + current.Name, + current.AutomationId, + current.ClassName, + current.FrameworkId, + current.ProcessId, + current.NativeWindowHandle, + current.IsOffscreen); + } + catch (Exception ex) + { + return "(属性读取失败) " + FormatException(ex); + } + + var patterns = new List(); + ProbePattern(element, GridPattern.Pattern, "Grid", patterns); + ProbePattern(element, TablePattern.Pattern, "Table", patterns); + ProbePattern(element, SelectionPattern.Pattern, "Selection", patterns); + ProbePattern(element, SelectionItemPattern.Pattern, "SelectionItem", patterns); + ProbePattern(element, ValuePattern.Pattern, "Value", patterns); + ProbePattern(element, TextPattern.Pattern, "Text", patterns); + description += " | Patterns=" + (patterns.Count == 0 ? "(无)" : string.Join(",", patterns.ToArray())); + + int childCount = 0; + string firstChildType = null; + try + { + AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(element); + while (child != null && childCount < maxChildren) + { + if (childCount == 0) + { + firstChildType = child.Current.ControlType == null + ? null + : child.Current.ControlType.ProgrammaticName; + } + + childCount++; + child = TreeWalker.ControlViewWalker.GetNextSibling(child); + } + } + catch (Exception ex) + { + description += " | 子元素读取失败:" + FormatException(ex); + return description; + } + + description += " | 子元素" + (childCount >= maxChildren ? "≥" : "=") + childCount + + (firstChildType == null ? string.Empty : "(首个:" + firstChildType + ")"); + return description; + } + + private static void ProbePattern(AutomationElement element, AutomationPattern pattern, string name, ICollection names) + { + try + { + object patternObject; + if (element.TryGetCurrentPattern(pattern, out patternObject)) + { + names.Add(name); + } + } + catch + { + names.Add(name + "?"); + } + } + + public UiaElementInfo Inspect(AutomationElement element) + { + var snapshot = new UiaElementInfo + { + Element = element, + IsAvailable = false + }; + + if (element == null) + { + snapshot.Error = "UIA 元素为空。"; + return snapshot; + } + + try + { + AutomationElement.AutomationElementInformation current = element.Current; + snapshot.Name = ReadString(delegate { return current.Name; }, snapshot, "Name"); + snapshot.AutomationId = ReadString(delegate { return current.AutomationId; }, snapshot, "AutomationId"); + snapshot.ControlType = ReadControlType(delegate { return current.ControlType; }, snapshot); + snapshot.ClassName = ReadString(delegate { return current.ClassName; }, snapshot, "ClassName"); + snapshot.FrameworkId = ReadString(delegate { return current.FrameworkId; }, snapshot, "FrameworkId"); + snapshot.NativeWindowHandle = ReadInt32(delegate { return current.NativeWindowHandle; }, snapshot, "NativeWindowHandle"); + snapshot.IsEnabled = ReadBoolean(delegate { return current.IsEnabled; }, snapshot, "IsEnabled"); + snapshot.IsOffscreen = ReadBoolean(delegate { return current.IsOffscreen; }, snapshot, "IsOffscreen"); + snapshot.ProcessId = ReadInt32(delegate { return current.ProcessId; }, snapshot, "ProcessId"); + snapshot.BoundingRectangle = ReadRectangle(delegate { return current.BoundingRectangle; }, snapshot, "BoundingRectangle"); + snapshot.HasKeyboardFocus = ReadBoolean(delegate { return current.HasKeyboardFocus; }, snapshot, "HasKeyboardFocus"); + snapshot.IsKeyboardFocusable = ReadBoolean(delegate { return current.IsKeyboardFocusable; }, snapshot, "IsKeyboardFocusable"); + snapshot.ProviderDescription = null; + // RuntimeId is a provider call and is only needed when saving a monitor entry, so it + // stays lazy here (see UiaElementInfo.EnsureRuntimeId). + + ReplacePatterns(snapshot, ReadSupportedPatterns(element, snapshot)); + snapshot.IsAvailable = true; + } + catch (Exception ex) + { + snapshot.Error = FormatException(ex); + } + + return snapshot; + } + + public UiaTreeNodeInfo ReadTree( + AutomationElement root, + int maxDepth, + int maxNodes, + TimeSpan timeout, + CancellationToken cancellationToken) + { + ValidateTreeArguments(maxDepth, maxNodes); + if (root == null) + { + return new UiaTreeNodeInfo + { + Element = Failure("UIA 根元素为空。"), + ChildrenComplete = false, + ChildrenError = "UiAutomationUnavailable" + }; + } + + var state = new ReadBudget(maxDepth, maxNodes, timeout, cancellationToken); + // One cache request activated for the whole walk: every element obtained below (bulk + // FindAll / walker) arrives with all of its properties already fetched, so a node costs + // no property round trips at all. Activating is the only way to make FindAll cached — + // there is no FindAll overload that takes a request. + CacheRequest cache = CreateSnapshotCache(); + cache.Activate(); + try + { + return ReadNode(root, 0, state, null); + } + finally + { + cache.Pop(); + } + } + + public UiaTreeNodeInfo ReadTree( + IntPtr handle, + int maxDepth, + int maxNodes, + TimeSpan timeout, + CancellationToken cancellationToken) + { + ValidateTreeArguments(maxDepth, maxNodes); + cancellationToken.ThrowIfCancellationRequested(); + var state = new ReadBudget(maxDepth, maxNodes, timeout, cancellationToken); + CacheRequest cache = CreateSnapshotCache(); + cache.Activate(); + try + { + AutomationElement root; + UiaElementInfo rootSnapshot; + try + { + root = AutomationElement.FromHandle(handle); + rootSnapshot = root == null ? Failure("AutomationElement.FromHandle 返回空。") : InspectCached(root); + } + catch (Exception ex) + { + rootSnapshot = Failure(FormatException(ex)); + root = null; + } + + if (root == null || !rootSnapshot.IsAvailable || rootSnapshot.Element == null) + { + return new UiaTreeNodeInfo + { + Element = rootSnapshot, + ChildrenComplete = false, + ChildrenError = "UiAutomationUnavailable" + }; + } + + return ReadNode(root, 0, state, rootSnapshot); + } + finally + { + cache.Pop(); + } + } + + private UiaTreeNodeInfo ReadNode( + AutomationElement element, + int depth, + ReadBudget state, + UiaElementInfo existingSnapshot) + { + state.ThrowIfStopped(); + UiaElementInfo snapshot = existingSnapshot ?? InspectCached(element); + if (!snapshot.IsAvailable && snapshot.Error != null && snapshot.Element == null) + { + snapshot.Element = element; + } + var node = new UiaTreeNodeInfo + { + Element = snapshot, + ChildrenComplete = true + }; + + if (depth >= state.MaxDepth) + { + try + { + AutomationElementCollection probe = element.FindAll(TreeScope.Children, Condition.TrueCondition); + if (probe == null || probe.Count == 0) + { + return node; + } + } + catch (Exception ex) + { + node.ChildrenComplete = false; + node.ChildrenError = FormatException(ex); + return node; + } + + node.ChildrenComplete = false; + node.ChildrenError = "MaxDepthReached"; + return node; + } + + try + { + // One bulk call per parent instead of one call per child plus one per sibling: with the + // snapshot cache attached, every returned child arrives fully populated, so a node + // costs the walker nothing at all. Child counts here are per-control, never the whole + // desktop (the walk never descends from the root window). + AutomationElementCollection children = element.FindAll(TreeScope.Children, Condition.TrueCondition); + foreach (AutomationElement child in children) + { + state.ThrowIfStopped(); + if (state.IsNodeLimitReached) + { + node.ChildrenComplete = false; + node.ChildrenError = "MaxNodesReached"; + break; + } + + state.CountNode(); + UiaTreeNodeInfo childNode = ReadNode(child, depth + 1, state, null); + node.Children.Add(childNode); + if (!childNode.ChildrenComplete) + { + node.ChildrenComplete = false; + if (string.IsNullOrEmpty(node.ChildrenError)) + { + node.ChildrenError = "DescendantIncomplete"; + } + } + + state.ThrowIfStopped(); + } + } + catch (OperationCanceledException) + { + node.ChildrenComplete = false; + node.ChildrenError = "Canceled"; + } + catch (TimeoutException) + { + node.ChildrenComplete = false; + node.ChildrenError = "TimedOut"; + } + catch (Exception ex) + { + node.ChildrenComplete = false; + node.ChildrenError = FormatException(ex); + } + + return node; + } + + private static void ValidateTreeArguments(int maxDepth, int maxNodes) + { + if (maxDepth < 0) + { + throw new ArgumentOutOfRangeException("maxDepth"); + } + + if (maxNodes < 1) + { + throw new ArgumentOutOfRangeException("maxNodes"); + } + } + + private static void ReplacePatterns(UiaElementInfo snapshot, IList patterns) + { + snapshot.SupportedPatterns.Clear(); + foreach (string pattern in patterns) + { + snapshot.SupportedPatterns.Add(pattern); + } + } + + private static List ReadSupportedPatterns(AutomationElement element, UiaElementInfo snapshot) + { + var names = new List(); + try + { + AutomationPattern[] patterns = element.GetSupportedPatterns(); + if (patterns != null) + { + foreach (AutomationPattern pattern in patterns) + { + if (pattern == null) + { + continue; + } + + PatternDescriptor descriptor = KnownPatterns.FirstOrDefault(p => p.Pattern == pattern); + string name = descriptor == null ? FormatPatternName(pattern.ProgrammaticName) : descriptor.Name; + if (!names.Contains(name)) + { + names.Add(name); + } + } + } + } + catch (Exception ex) + { + snapshot.PropertyErrors.Add("SupportedPatterns: " + FormatException(ex)); + } + + // Only when the provider returned nothing at all: some older providers expose an empty + // pattern array. Probing all known patterns unconditionally would cost ~10 extra + // cross-process calls per element, which a full tree read cannot afford. + if (names.Count == 0) + { + foreach (PatternDescriptor descriptor in KnownPatterns) + { + try + { + object ignored; + if (element.TryGetCurrentPattern(descriptor.Pattern, out ignored) && + !names.Contains(descriptor.Name)) + { + names.Add(descriptor.Name); + } + } + catch (Exception ex) + { + snapshot.PropertyErrors.Add(descriptor.Name + ": " + FormatException(ex)); + } + } + } + + return names; + } + + /// + /// Turns a raw programmatic name such as "TransformPatternIdentifiers.Pattern" into the + /// readable "TransformPattern" that the other pattern names use. + /// + private static string FormatPatternName(string programmaticName) + { + if (string.IsNullOrEmpty(programmaticName)) + { + return "(未知模式)"; + } + + string name = programmaticName.Replace("PatternIdentifiers", string.Empty); + return name.EndsWith(".Pattern", StringComparison.Ordinal) + ? name.Substring(0, name.Length - ".Pattern".Length) + : name; + } + + private static string ReadRuntimeId(AutomationElement element, UiaElementInfo snapshot) + { + try + { + int[] id = element.GetRuntimeId(); + return id == null ? null : string.Join(".", id.Select(value => value.ToString()).ToArray()); + } + catch (Exception ex) + { + snapshot.PropertyErrors.Add("RuntimeId: " + FormatException(ex)); + return null; + } + } + + private static string ReadControlType(Func getter, UiaElementInfo snapshot) + { + try + { + ControlType controlType = getter(); + return controlType == null ? null : controlType.ProgrammaticName; + } + catch (Exception ex) + { + snapshot.PropertyErrors.Add("ControlType: " + FormatException(ex)); + return null; + } + } + + private static string ReadString(Func getter, UiaElementInfo snapshot, string propertyName) + { + try + { + return getter(); + } + catch (Exception ex) + { + snapshot.PropertyErrors.Add(propertyName + ": " + FormatException(ex)); + return null; + } + } + + private static int ReadInt32(Func getter, UiaElementInfo snapshot, string propertyName) + { + try + { + return getter(); + } + catch (Exception ex) + { + snapshot.PropertyErrors.Add(propertyName + ": " + FormatException(ex)); + return 0; + } + } + + private static bool? ReadBoolean(Func getter, UiaElementInfo snapshot, string propertyName) + { + try + { + return getter(); + } + catch (Exception ex) + { + snapshot.PropertyErrors.Add(propertyName + ": " + FormatException(ex)); + return null; + } + } + + private static NativeRectangleInfo ReadRectangle(Func getter, UiaElementInfo snapshot, string propertyName) + { + try + { + return ToRectangleInfo(getter()); + } + catch (Exception ex) + { + snapshot.PropertyErrors.Add(propertyName + ": " + FormatException(ex)); + return new NativeRectangleInfo(); + } + } + + private static NativeRectangleInfo ToRectangleInfo(System.Windows.Rect rectangle) + { + if (rectangle.IsEmpty || double.IsInfinity(rectangle.Left) || double.IsInfinity(rectangle.Top) || + double.IsInfinity(rectangle.Right) || double.IsInfinity(rectangle.Bottom) || + rectangle.Left < int.MinValue || rectangle.Top < int.MinValue || + rectangle.Right > int.MaxValue || rectangle.Bottom > int.MaxValue) + { + return new NativeRectangleInfo(); + } + + return new NativeRectangleInfo( + (int)Math.Round(rectangle.Left), + (int)Math.Round(rectangle.Top), + (int)Math.Round(rectangle.Right), + (int)Math.Round(rectangle.Bottom)); + } + + private static UiaElementInfo Failure(string error) + { + return new UiaElementInfo + { + IsAvailable = false, + Error = error + }; + } + + private static string FormatException(Exception exception) + { + if (exception is ElementNotAvailableException) + { + return "ElementNotAvailable: " + exception.Message; + } + + if (exception is COMException) + { + return string.Format("COM 0x{0:X8}: {1}", exception.HResult, exception.Message); + } + + return exception.GetType().Name + ": " + exception.Message; + } + + private sealed class PatternDescriptor + { + internal PatternDescriptor(string name, AutomationPattern pattern) + { + Name = name; + Pattern = pattern; + } + + internal string Name { get; private set; } + internal AutomationPattern Pattern { get; private set; } + } + } +} diff --git a/src/pacs_win_uia/Services/Win32TreeReader.cs b/src/pacs_win_uia/Services/Win32TreeReader.cs new file mode 100644 index 0000000..db4546e --- /dev/null +++ b/src/pacs_win_uia/Services/Win32TreeReader.cs @@ -0,0 +1,360 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Interop; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// 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 + /// reader cannot hang on a wedged provider. + /// + /// Only titles need a cross-process message (WM_GETTEXT), so they go through SendMessageTimeout + /// and are skipped for hidden windows. + /// + public sealed class Win32TreeReader + { + /// HWND_MESSAGE: parent of message-only windows, which are never shown. + private static readonly IntPtr HwndMessage = new IntPtr(-3); + + public ControlTreeNode Read(IntPtr rootHandle, ControlTreeOptions options, CancellationToken cancellationToken) + { + if (options == null) + { + options = new ControlTreeOptions(); + } + + var budget = new ReadBudget(options.MaxDepth, options.MaxNodes, options.Timeout, cancellationToken); + var root = new ControlTreeNode + { + Source = ControlTreeSource.Win32, + Window = CaptureWindow(rootHandle, options, out string rootError) + }; + if (root.Window == null) + { + root.ChildrenComplete = false; + root.ChildrenError = rootError ?? "根窗口无效。"; + return root; + } + + var handles = new List(); + bool enumerated = NativeMethods.EnumChildWindows( + rootHandle, + delegate(IntPtr hWnd, IntPtr lParam) + { + handles.Add(hWnd); + return true; + }, + IntPtr.Zero); + + var processNameCache = new Dictionary(); + int nodeCount = 0; + bool truncated = false; + bool skippedInvalid = false; + + // EnumChildWindows already returns every descendant (grandchildren included), so the + // structure is rebuilt from GA_PARENT instead of enumerating level by level. + var childrenByParent = new Dictionary>(); + foreach (IntPtr handle in handles) + { + if (handle == IntPtr.Zero || !NativeMethods.IsWindow(handle)) + { + skippedInvalid = true; + continue; + } + + if (IsMessageOnly(handle)) + { + continue; + } + + if (nodeCount >= options.MaxNodes) + { + truncated = true; + break; + } + + nodeCount++; + IntPtr parent = NativeMethods.GetAncestor(handle, NativeMethods.GA_PARENT); + List siblings; + if (!childrenByParent.TryGetValue(parent, out siblings)) + { + siblings = new List(); + childrenByParent[parent] = siblings; + } + + siblings.Add(handle); + } + + AppLog.Debug("Win32 树:EnumChildWindows 返回 " + handles.Count + " 个句柄,纳入 " + nodeCount + " 个节点。"); + BuildChildren(root, rootHandle, childrenByParent, processNameCache, options, budget, 0); + + if (!enumerated) + { + if (nodeCount == 0) + { + // EnumChildWindows reports failure for a window with no children at all; that is + // a result, not an error: the window really has no child windows. + AppLog.Info("Win32 树:该窗口没有子窗口(EnumChildWindows 未返回任何句柄)。"); + } + else + { + root.ChildrenComplete = false; + root.ChildrenError = "EnumChildWindows 失败,Win32 错误码 " + Marshal.GetLastWin32Error(); + } + } + + if (truncated) + { + root.ChildrenComplete = false; + root.ChildrenError = "达到节点上限 " + options.MaxNodes + ",结果被截断。"; + } + + if (skippedInvalid) + { + AppLog.Debug("Win32 树:跳过了枚举期间已失效的句柄。"); + } + + return root; + } + + private static void BuildChildren( + ControlTreeNode parentNode, + IntPtr parentHandle, + IDictionary> childrenByParent, + IDictionary processNameCache, + ControlTreeOptions options, + ReadBudget budget, + int depth) + { + List children; + if (!childrenByParent.TryGetValue(parentHandle, out children)) + { + return; + } + + foreach (IntPtr child in children) + { + try + { + budget.ThrowIfStopped(); + budget.CountNode(); + } + catch (TimeoutException ex) + { + parentNode.ChildrenComplete = false; + parentNode.ChildrenError = ex.Message; + return; + } + catch (OperationCanceledException) + { + parentNode.ChildrenComplete = false; + parentNode.ChildrenError = "Canceled"; + return; + } + + string error; + NativeWindowInfo window = CaptureWindow(child, options, out error, processNameCache); + var node = new ControlTreeNode + { + Source = ControlTreeSource.Win32, + Window = window + }; + parentNode.Children.Add(node); + + if (window == null) + { + node.ChildrenComplete = false; + node.ChildrenError = error ?? "窗口已失效。"; + continue; + } + + if (depth + 1 >= budget.MaxDepth) + { + bool hasChildren = childrenByParent.ContainsKey(child); + if (hasChildren) + { + node.ChildrenComplete = false; + node.ChildrenError = "MaxDepthReached"; + } + + continue; + } + + BuildChildren(node, child, childrenByParent, processNameCache, options, budget, depth + 1); + } + } + + /// + /// One GetWindowInfo call replaces GetWindowRect + GetClientRect + ClientToScreen + style + /// reads; only the class name and the (bounded) title are separate. + /// + private static NativeWindowInfo CaptureWindow( + IntPtr handle, + ControlTreeOptions options, + out string error, + IDictionary processNameCache = null) + { + error = null; + if (handle == IntPtr.Zero || !NativeMethods.IsWindow(handle)) + { + error = "HWND 无效。"; + return null; + } + + var errors = new List(); + var result = new NativeWindowInfo(handle); + try + { + var info = new NativeMethods.WINDOWINFO(); + info.cbSize = Marshal.SizeOf(typeof(NativeMethods.WINDOWINFO)); + if (NativeMethods.GetWindowInfo(handle, ref info)) + { + result.WindowBounds = new NativeRectangleInfo( + info.rcWindow.Left, info.rcWindow.Top, info.rcWindow.Right, info.rcWindow.Bottom); + result.ClientBounds = new NativeRectangleInfo( + info.rcClient.Left, info.rcClient.Top, info.rcClient.Right, info.rcClient.Bottom); + result.IsVisible = (info.dwStyle & NativeMethods.WS_VISIBLE) != 0; + } + else + { + errors.Add("GetWindowInfo 失败,Win32 错误码 " + Marshal.GetLastWin32Error() + "。"); + } + + if (IsCloaked(handle)) + { + // UWP/ApplicationFrameHost windows look visible but are cloaked by DWM. + result.IsVisible = false; + errors.Add("窗口已被 DWM 隐藏(cloaked)。"); + } + + result.IsMinimized = NativeMethods.IsIconic(handle); + + var className = new StringBuilder(256); + if (NativeMethods.GetClassName(handle, className, className.Capacity) > 0) + { + result.ClassName = className.ToString(); + } + + uint processId; + if (NativeMethods.GetWindowThreadProcessId(handle, out processId) != 0) + { + result.ProcessId = unchecked((int)processId); + result.ProcessName = NativeWindowService.TryGetProcessName(result.ProcessId, errors, processNameCache); + } + else + { + errors.Add("GetWindowThreadProcessId 失败。"); + } + + result.ParentHwndHex = NativeWindowInfo.FormatHandle( + NativeMethods.GetAncestor(handle, NativeMethods.GA_PARENT)); + result.RootHwndHex = NativeWindowInfo.FormatHandle( + NativeMethods.GetAncestor(handle, NativeMethods.GA_ROOT)); + + if (options.ReadWindowTitles && result.IsVisible) + { + result.Title = ReadWindowTitle(handle, options.TitleReadTimeoutMs, errors); + } + else + { + result.Title = string.Empty; + } + } + catch (Exception ex) + { + errors.Add(ex.GetType().Name + ": " + ex.Message); + } + + if (errors.Count > 0) + { + result.Error = string.Join(" | ", errors.ToArray()); + error = result.Error; + } + + return result; + } + + /// + /// 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. + /// + private static string ReadWindowTitle(IntPtr handle, int timeoutMs, ICollection errors) + { + const int BufferLength = 512; + try + { + int length = NativeMethods.GetWindowTextLength(handle); + if (length <= 0) + { + return string.Empty; + } + + var builder = new StringBuilder(Math.Min(Math.Max(length + 1, 256), BufferLength)); + IntPtr result; + IntPtr sent = NativeMethods.SendMessageTimeout( + handle, + NativeMethods.WM_GETTEXT, + new IntPtr(builder.Capacity), + builder, + NativeMethods.SMTO_ABORTIFHUNG, + (uint)Math.Max(1, timeoutMs), + out result); + if (sent == IntPtr.Zero) + { + errors.Add("读取窗口标题超时(目标可能无响应)。"); + return string.Empty; + } + + return builder.ToString(); + } + catch (Exception ex) + { + errors.Add("窗口标题: " + ex.GetType().Name); + return string.Empty; + } + } + + private static bool IsMessageOnly(IntPtr handle) + { + IntPtr parent = NativeMethods.GetAncestor(handle, NativeMethods.GA_PARENT); + if (parent == HwndMessage) + { + return true; + } + + var className = new StringBuilder(32); + if (NativeMethods.GetClassName(handle, className, className.Capacity) > 0) + { + return string.Equals(className.ToString(), "Message", StringComparison.Ordinal); + } + + return false; + } + + private static bool IsCloaked(IntPtr handle) + { + try + { + int cloaked; + if (NativeMethods.DwmGetWindowAttribute( + handle, NativeMethods.DWMWA_CLOAKED, out cloaked, sizeof(int)) != 0) + { + return false; + } + + return cloaked != 0; + } + catch (Exception) + { + // dwmapi is present on Win7+, but a failure here must never fail the read. + return false; + } + } + } +} diff --git a/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs b/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs new file mode 100644 index 0000000..1529f36 --- /dev/null +++ b/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs @@ -0,0 +1,959 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Models; +using pacs_win_uia.Services; + +namespace pacs_win_uia.UI +{ + public sealed class ControlLocatedEventArgs : EventArgs + { + public ControlLocatedEventArgs( + Models.ControlMonitorDefinition definition, + Models.ControlTreeNode node, + Models.NativeRectangleInfo bounds, + IList steps) + { + Definition = definition; + Node = node; + Bounds = bounds; + Steps = steps; + } + + 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; } + } + + public sealed class DefinitionSelectedEventArgs : EventArgs + { + public DefinitionSelectedEventArgs(Models.ControlMonitorDefinition definition) + { + Definition = definition; + } + + 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; } + + public Exception Exception { get; private set; } + } + + /// + /// Editor for the control monitor definitions: which control, on which page, mapped to which + /// 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 + { + private const int ColumnEnabled = 0; + private const int ColumnPath = 1; + private const int ColumnAlias = 2; + private const int ColumnSource = 3; + private const int ColumnValueKey = 4; + private const int ColumnFocus = 5; + private const int ColumnTimeout = 6; + + private readonly ControlMonitorStore _store; + private readonly ControlLocatorBuilder _locatorBuilder; + private readonly ControlLocatorService _locatorService; + private readonly BindingList _definitions; + 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; + private readonly DataGridViewComboBoxColumn _valueKeyColumn; + private ControlTreeNode _currentNode; + private NativeWindowInfo _currentWindow; + private bool _dirty; + + public ControlMonitorEditorControl() + : this(new ControlMonitorStore(), new ControlLocatorBuilder()) + { + } + + public ControlMonitorEditorControl(ControlMonitorStore store, ControlLocatorBuilder locatorBuilder) + { + _store = store ?? throw new ArgumentNullException("store"); + _locatorBuilder = locatorBuilder ?? throw new ArgumentNullException("locatorBuilder"); + _locatorService = new ControlLocatorService(); + _definitions = new BindingList(); + _bindingSource = new BindingSource(); + + var toolbar = new FlowLayoutPanel + { + Dock = DockStyle.Top, + Height = 34, + Padding = new Padding(2), + WrapContents = false + }; + _addButton = new Button { Text = "添加当前控件", AutoSize = true, Enabled = false }; + _deleteButton = new Button { Text = "删除选中", AutoSize = true }; + _saveButton = new Button { Text = "保存", AutoSize = true }; + _reloadButton = new Button { Text = "重载", AutoSize = true }; + _locateButton = new Button { Text = "定位到控件", AutoSize = true }; + _refreshStatesButton = new Button { Text = "刷新状态", AutoSize = true }; + toolbar.Controls.Add(_addButton); + toolbar.Controls.Add(_deleteButton); + toolbar.Controls.Add(_saveButton); + toolbar.Controls.Add(_reloadButton); + toolbar.Controls.Add(_locateButton); + toolbar.Controls.Add(_refreshStatesButton); + + _grid = new DataGridView + { + Dock = DockStyle.Fill, + AutoGenerateColumns = false, + AllowUserToAddRows = false, + AllowUserToDeleteRows = false, + AllowUserToResizeRows = false, + MultiSelect = false, + SelectionMode = DataGridViewSelectionMode.CellSelect, + EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2, + RowHeadersWidth = 28 + }; + _grid.Columns.Add(new DataGridViewCheckBoxColumn + { + HeaderText = "启用", + DataPropertyName = "Enabled", + Width = 44, + FlatStyle = FlatStyle.Flat + }); + _grid.Columns.Add(new DataGridViewTextBoxColumn + { + HeaderText = "控件Path", + DataPropertyName = "ControlPath", + ReadOnly = true, + AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, + FillWeight = 46, + MinimumWidth = 150 + }); + var sourceColumn = new DataGridViewComboBoxColumn + { + HeaderText = "来源", + DataPropertyName = "Source", + Width = 88, + FlatStyle = FlatStyle.Flat + }; + sourceColumn.Items.AddRange(new object[] + { + ControlSourcePreference.Auto, + ControlSourcePreference.Uia, + ControlSourcePreference.Msaa, + ControlSourcePreference.Win32 + }); + _grid.Columns.Add(sourceColumn); + + // Editable combo: the common keys are offered, but any property name can be typed + // (CellValidating adds an unknown key to the item list so the grid accepts it). + _valueKeyColumn = new DataGridViewComboBoxColumn + { + HeaderText = "valueKey", + DataPropertyName = "ValueKey", + Width = 130, + FlatStyle = FlatStyle.Flat, + DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox, + DisplayStyleForCurrentCellOnly = true + }; + foreach (string key in ControlValueKeys.For(ControlSourcePreference.Auto)) + { + _valueKeyColumn.Items.Add(key); + } + + _grid.Columns.Add(_valueKeyColumn); + var focusColumn = new DataGridViewTextBoxColumn + { + HeaderText = "焦点", + DataPropertyName = "FocusState", + ReadOnly = true, + Width = 90 + }; + _grid.Columns.Add(focusColumn); + _grid.Columns.Add(new DataGridViewTextBoxColumn + { + HeaderText = "超时秒", + DataPropertyName = "TimeoutSeconds", + Width = 60 + }); + _grid.Columns.Add(new DataGridViewTextBoxColumn + { + HeaderText = "别名", + DataPropertyName = "ContentKey", + AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, + FillWeight = 20, + MinimumWidth = 90 + }); + + _messageLabel = new Label + { + Dock = DockStyle.Bottom, + Height = 44, + Padding = new Padding(2), + ForeColor = Color.DarkSlateGray, + AutoEllipsis = true + }; + + Controls.Add(_grid); + Controls.Add(toolbar); + Controls.Add(_messageLabel); + _bindingSource.DataSource = _definitions; + _grid.DataSource = _bindingSource; + + _addButton.Click += delegate { AddCurrentControl(); }; + _deleteButton.Click += delegate { DeleteSelected(); }; + _saveButton.Click += delegate { Save(); }; + _reloadButton.Click += delegate { ReloadWithConfirmation(); }; + _locateButton.Click += delegate { LocateCurrentDefinition(); }; + _refreshStatesButton.Click += delegate { RefreshAllStates(); }; + // Clicking the row-header triangle jumps to the control on screen. + _grid.RowHeaderMouseClick += delegate { LocateCurrentDefinition(); }; + _grid.SelectionChanged += delegate { RaiseDefinitionSelected(); }; + _grid.CellValueChanged += OnCellValueChanged; + _grid.RowsAdded += delegate { MarkDirty(); }; + _grid.UserDeletedRow += delegate { MarkDirty(); }; + _grid.DataError += GridOnDataError; + _grid.CellEndEdit += delegate { RefreshValidation(); }; + _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 + // object until the user happens to leave the cell. + if (_grid.IsCurrentCellDirty) + { + _grid.CommitEdit(DataGridViewDataErrorContexts.Commit); + } + }; + _grid.SelectionChanged += delegate { ShowSelectedLocator(); }; + + LoadFromStore(); + } + + 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. + public event EventHandler DefinitionSelected; + + 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; + _currentWindow = window; + _addButton.Enabled = node != null && (node.Uia != null || node.Msaa != null || node.Window != null); + } + + /// Commits any cell being edited; call before hiding the form or saving. + public void CommitEdits() + { + try + { + _bindingSource.EndEdit(); + _grid.EndEdit(); + } + catch (Exception ex) + { + AppLog.Warn("提交控件监控列表编辑状态失败。", ex); + } + } + + public void LoadFromStore() + { + CommitEdits(); + + List loaded; + try + { + loaded = new List(_store.Load()); + } + catch (Exception ex) + { + AppLog.Error("加载控件监控定义失败:" + _store.FilePath, ex); + Report("加载控件监控定义失败(文件保留原样):" + ex.Message, ex); + RefreshValidation(); + return; + } + + _definitions.RaiseListChangedEvents = false; + try + { + _definitions.Clear(); + foreach (ControlMonitorDefinition definition in loaded) + { + _definitions.Add(definition); + } + } + finally + { + _definitions.RaiseListChangedEvents = true; + } + + _bindingSource.ResetBindings(false); + _dirty = false; + AppLog.Info("已加载 " + _definitions.Count + " 条控件监控定义:" + _store.FilePath); + RefreshValidation(); + Report("已加载 " + _definitions.Count + " 条控件监控定义。", null); + } + + private void AddCurrentControl() + { + ControlTreeNode node = _currentNode; + if (node == null) + { + Report("请先拾取或选中一个控件。", null); + return; + } + + ControlLocatorBuildResult locator; + try + { + if (node.Source == ControlTreeSource.Msaa) + { + locator = _locatorBuilder.BuildFromMsaa(node.Msaa, _currentWindow); + } + else if (node.Source == ControlTreeSource.Win32) + { + locator = _locatorBuilder.BuildFromWin32(node.Window, _currentWindow); + } + else + { + locator = _locatorBuilder.BuildFromUia(node.Uia, _currentWindow); + } + } + catch (Exception ex) + { + AppLog.Error("生成控件定位信息失败。", ex); + Report("生成控件定位信息失败:" + ex.Message, ex); + return; + } + + var definition = new ControlMonitorDefinition + { + ControlPath = string.IsNullOrEmpty(locator.DisplayPath) + ? "(" + node.Source + ":窗口本身)" + : "[" + node.Source + "] " + locator.DisplayPath, + Source = locator.Source, + ProcessName = locator.ProcessName, + WindowClass = locator.WindowClass, + WindowTitleKeyword = locator.WindowTitleKeyword, + MsaaPathKey = locator.MsaaPathKey, + RuntimeId = locator.RuntimeId, + ValueKey = locator.ValueKey, + Value = locator.Value, + PageFeatures = BuildPageFeatures(locator), + ContentKey = SuggestContentKey(node) + }; + if (locator.UiaPath != null) + { + definition.UiaPath.AddRange(locator.UiaPath); + } + + if (locator.Win32Path != null) + { + definition.Win32Path.AddRange(locator.Win32Path); + } + + CommitEdits(); + _definitions.Add(definition); + _bindingSource.Position = _definitions.Count - 1; + MarkDirty(); + RefreshValidation(); + ShowSelectedLocator(); + Report(locator.IsComplete + ? "已添加当前控件(" + locator.Source + ",属性 " + locator.ValueKey + "),请确认后保存。" + : "已添加当前控件,但定位路径不完整:" + (locator.Note ?? "未知原因"), null); + } + + /// The page feature suggestion is exactly the window identification that gets saved. + private static string BuildPageFeatures(ControlLocatorBuildResult locator) + { + var builder = new StringBuilder(); + if (!string.IsNullOrEmpty(locator.ProcessName)) + { + builder.Append("进程=").Append(locator.ProcessName); + } + + if (!string.IsNullOrEmpty(locator.WindowTitleKeyword)) + { + if (builder.Length > 0) + { + builder.Append(";"); + } + + builder.Append("标题关键词=").Append(locator.WindowTitleKeyword); + } + + if (!string.IsNullOrEmpty(locator.WindowClass)) + { + if (builder.Length > 0) + { + builder.Append(";"); + } + + builder.Append("窗口类=").Append(locator.WindowClass); + } + + return builder.ToString(); + } + + private void DeleteSelected() + { + CommitEdits(); + int index = _bindingSource.Position; + if (index < 0 || index >= _definitions.Count) + { + Report("请先选中要删除的行。", null); + return; + } + + ControlMonitorDefinition removed = _definitions[index]; + _definitions.RemoveAt(index); + MarkDirty(); + RefreshValidation(); + Report("已删除:" + (removed == null ? "(空行)" : removed.ToString()), null); + } + + private void Save() + { + CommitEdits(); + IList errors = ControlMonitorStore.TryValidate(GetDefinitions()); + if (errors.Count > 0) + { + RefreshValidation(); + Report("有 " + errors.Count + " 处问题,未保存:" + errors[0], null); + return; + } + + try + { + _store.Save(GetDefinitions()); + _dirty = false; + RefreshValidation(); + AppLog.Info("已保存 " + _definitions.Count + " 条控件监控定义:" + _store.FilePath); + Report("已保存 " + _definitions.Count + " 条定义:" + _store.FilePath, null); + } + catch (Exception ex) + { + AppLog.Error("保存控件监控定义失败:" + _store.FilePath, ex); + Report("保存失败:" + ex.Message, ex); + } + } + + private void ReloadWithConfirmation() + { + if (_dirty) + { + DialogResult answer = MessageBox.Show( + this, + "重载会丢弃尚未保存的修改,继续吗?", + "控件监控列表", + MessageBoxButtons.YesNo, + MessageBoxIcon.Warning); + if (answer != DialogResult.Yes) + { + return; + } + } + + LoadFromStore(); + } + + private void MarkDirty() + { + _dirty = true; + } + + /// Offers the keys that make sense for the row's source, while still allowing any text. + private void GridOnCellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) + { + if (e.ColumnIndex != ColumnValueKey) + { + return; + } + + var column = _grid.Columns[ColumnValueKey] as DataGridViewComboBoxColumn; + if (column == null) + { + return; + } + + ControlSourcePreference preference = ControlSourcePreference.Auto; + if (e.RowIndex >= 0 && e.RowIndex < _definitions.Count && _definitions[e.RowIndex] != null) + { + preference = _definitions[e.RowIndex].Source; + } + + var keys = new List(); + foreach (string key in ControlValueKeys.For(preference)) + { + if (!keys.Contains(key)) + { + keys.Add(key); + } + } + + column.Items.Clear(); + foreach (string key in keys) + { + column.Items.Add(key); + } + + if (_grid.EditingControl is ComboBox) + { + ((ComboBox)_grid.EditingControl).DropDownStyle = ComboBoxStyle.DropDown; + } + } + + /// Accepts a hand-typed property name by adding it to the combo's items. + private void GridOnCellValidating(object sender, DataGridViewCellValidatingEventArgs e) + { + if (e.ColumnIndex != ColumnValueKey || _valueKeyColumn == null) + { + return; + } + + string text = Convert.ToString(e.FormattedValue); + if (!string.IsNullOrEmpty(text) && !_valueKeyColumn.Items.Contains(text)) + { + _valueKeyColumn.Items.Add(text); + } + } + + private void OnCellValueChanged(object sender, DataGridViewCellEventArgs e) + { + MarkDirty(); + if (e.ColumnIndex == ColumnEnabled || e.ColumnIndex == ColumnSource || + e.ColumnIndex == ColumnValueKey || e.ColumnIndex == ColumnTimeout) + { + RefreshValidation(); + } + } + + /// + /// Resolves the selected entry and asks the owner to highlight it on screen. Also records the + /// focus state, which is exactly what the 焦点 column shows. + /// + public void LocateCurrentDefinition() + { + CommitEdits(); + ControlMonitorDefinition definition = SelectedDefinition(); + if (definition == null) + { + Report("请先选中要定位的监控条目。", null); + return; + } + + TimeSpan timeout = definition.TimeoutSeconds > 0 + ? TimeSpan.FromSeconds(definition.TimeoutSeconds) + : TimeSpan.FromSeconds(5); + var steps = new List(); + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + string error; + IntPtr window = _locatorService.FindTargetWindow(definition, steps, out error); + if (window == IntPtr.Zero) + { + MarkRowError(definition, error ?? "没有找到目标窗口。"); + Report("定位失败:" + error, null); + return; + } + + ControlResolution resolution = _locatorService.Resolve(definition, window, steps); + if (!resolution.Found) + { + MarkRowError(definition, resolution.Error ?? "控件未定位到。"); + Report("定位失败:" + resolution.Error, null); + return; + } + + string focus; + string focusError; + if (ControlValueReader.TryRead(resolution.Node, ControlValueKeys.Focused, new ListReadOptions(), out focus, out focusError)) + { + definition.FocusState = focus; + } + else + { + definition.FocusState = "(读不到)"; + steps.Add("焦点状态:" + focusError); + } + + _grid.Refresh(); + stopwatch.Stop(); + AppLog.Info(string.Format("定位到控件:{0};来源 {1};焦点 {2};耗时 {3} ms;步骤:{4}", + definition.ContentKey, resolution.ResolvedSource, definition.FocusState, + stopwatch.ElapsedMilliseconds, string.Join(" / ", steps.ToArray()))); + + EventHandler handler = ControlLocated; + if (handler != null) + { + handler(this, new ControlLocatedEventArgs(definition, resolution.Node, + BoundsOf(resolution.Node), steps)); + } + + Report(string.Format("已定位到「{0}」({1}),焦点:{2}", + definition.ContentKey, resolution.ResolvedSource, definition.FocusState), null); + } + + /// + /// Locates every enabled entry and refreshes its focus state. Each entry is timed on its own, + /// so one missing control cannot delay the others. + /// + public void RefreshAllStates() + { + CommitEdits(); + int located = 0; + int failed = 0; + foreach (ControlMonitorDefinition definition in _definitions) + { + if (definition == null || !definition.Enabled) + { + continue; + } + + try + { + var steps = new List(); + string error; + IntPtr window = _locatorService.FindTargetWindow(definition, steps, out error); + if (window == IntPtr.Zero) + { + definition.FocusState = "(未找到)"; + MarkRowError(definition, error ?? "没有找到目标窗口。"); + failed++; + continue; + } + + ControlResolution resolution = _locatorService.Resolve(definition, window, steps); + if (!resolution.Found) + { + definition.FocusState = "(未找到)"; + MarkRowError(definition, resolution.Error ?? "控件未定位到。"); + failed++; + continue; + } + + string focus; + string focusError; + definition.FocusState = ControlValueReader.TryRead( + resolution.Node, ControlValueKeys.Focused, new ListReadOptions(), out focus, out focusError) + ? focus + : "(读不到)"; + SetRowError(definition, null); + located++; + } + catch (Exception ex) + { + definition.FocusState = "(异常)"; + MarkRowError(definition, ex.Message); + failed++; + } + } + + _grid.Refresh(); + Report(string.Format("状态刷新完成:成功 {0} 条,失败 {1} 条(每条独立计时)。", located, failed), null); + } + + private static NativeRectangleInfo BoundsOf(ControlTreeNode node) + { + if (node == null) + { + return null; + } + + if (node.Uia != null && node.Uia.BoundingRectangle != null && node.Uia.BoundingRectangle.IsValid) + { + return node.Uia.BoundingRectangle; + } + + if (node.Msaa != null && node.Msaa.Location != null && node.Msaa.Location.IsValid) + { + return node.Msaa.Location; + } + + return node.Window == null ? null : node.Window.WindowBounds; + } + + 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); + } + + private void SetRowError(ControlMonitorDefinition definition, string error) + { + int index = _definitions.IndexOf(definition); + if (index >= 0 && index < _grid.Rows.Count) + { + _grid.Rows[index].ErrorText = error ?? string.Empty; + } + } + + private void RaiseDefinitionSelected() + { + EventHandler handler = DefinitionSelected; + if (handler != null) + { + handler(this, new DefinitionSelectedEventArgs(SelectedDefinition())); + } + } + + private void ShowSelectedLocator() + { + int index = _bindingSource.Position; + if (index < 0 || index >= _definitions.Count) + { + return; + } + + ControlMonitorDefinition definition = _definitions[index]; + if (definition == null) + { + return; + } + + var builder = new StringBuilder(); + builder.Append("定位:来源=").Append(definition.Source) + .Append(";进程=").Append(string.IsNullOrEmpty(definition.ProcessName) ? "(未记录)" : definition.ProcessName) + .Append(";窗口类=").Append(string.IsNullOrEmpty(definition.WindowClass) ? "(未记录)" : definition.WindowClass); + if (definition.UiaPath != null && definition.UiaPath.Count > 0) + { + builder.Append(";UIA=").Append(ControlLocatorFormat.DescribeUiaPath(definition.UiaPath)); + } + + if (!string.IsNullOrEmpty(definition.MsaaPathKey)) + { + builder.Append(";MSAA=").Append(definition.MsaaPathKey); + } + + if (definition.Win32Path != null && definition.Win32Path.Count > 0) + { + builder.Append(";Win32=").Append(ControlLocatorFormat.DescribeWin32Path(definition.Win32Path)); + } + + if (!string.IsNullOrEmpty(definition.RuntimeId)) + { + builder.Append(";RuntimeId=").Append(definition.RuntimeId); + } + + _messageLabel.ForeColor = Color.DarkSlateGray; + _messageLabel.Text = builder.ToString(); + } + + /// + /// 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. + /// + private void RefreshValidation() + { + IList errors = ControlMonitorStore.TryValidate(GetDefinitions()); + foreach (DataGridViewRow row in _grid.Rows) + { + row.ErrorText = string.Empty; + } + + var summary = new List(); + foreach (ControlMonitorValidationError error in errors) + { + if (!summary.Contains(error.Message)) + { + summary.Add(error.Message); + } + + if (error.Index >= 0 && error.Index < _grid.Rows.Count) + { + DataGridViewRow row = _grid.Rows[error.Index]; + row.ErrorText = string.IsNullOrEmpty(row.ErrorText) + ? error.Message + : row.ErrorText + ";" + error.Message; + } + } + + if (summary.Count == 0) + { + _messageLabel.ForeColor = Color.DarkSlateGray; + _messageLabel.Text = _definitions.Count == 0 + ? "还没有监控定义。选中目标控件后点击“添加当前控件”。" + : "校验通过,共 " + _definitions.Count + " 条定义。"; + return; + } + + var builder = new StringBuilder(); + for (int index = 0; index < summary.Count && index < 3; index++) + { + if (index > 0) + { + builder.Append(";"); + } + + builder.Append(summary[index]); + } + + if (summary.Count > 3) + { + builder.Append(" 等共 ").Append(summary.Count).Append(" 类问题。"); + } + + _messageLabel.ForeColor = Color.Firebrick; + _messageLabel.Text = builder.ToString(); + } + + private void GridOnDataError(object sender, DataGridViewDataErrorEventArgs e) + { + // Never let a rejected value escalate into an unhandled exception. + e.Cancel = true; + AppLog.Warn("控件监控列表单元格错误:" + e.Exception); + } + + private IList GetDefinitions() + { + return new List(_definitions); + } + + private string SuggestContentKey(ControlTreeNode node) + { + string source = null; + if (node.Source == ControlTreeSource.Msaa && node.Msaa != null) + { + source = node.Msaa.Name; + } + else if (node.Source == ControlTreeSource.Win32 && node.Window != null) + { + source = node.Window.Title; + } + else if (node.Uia != null) + { + source = node.Uia.AutomationId; + if (string.IsNullOrEmpty(source)) + { + source = node.Uia.Name; + } + } + + string candidate = SanitizeKey(source); + if (candidate == null) + { + candidate = "control"; + } + + string key = candidate; + int suffix = 2; + while (ContainsKey(key)) + { + key = candidate + suffix; + suffix++; + } + + return key; + } + + private bool ContainsKey(string key) + { + foreach (ControlMonitorDefinition definition in _definitions) + { + if (definition != null && string.Equals(definition.ContentKey, key, StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } + + /// + /// 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. + /// + private static string SanitizeKey(string value) + { + if (string.IsNullOrEmpty(value)) + { + return null; + } + + var builder = new StringBuilder(value.Length); + foreach (char character in value) + { + bool allowed = (character >= 'a' && character <= 'z') + || (character >= 'A' && character <= 'Z') + || (character >= '0' && character <= '9') + || character == '_' || character == '.' || character == '-'; + if (allowed) + { + builder.Append(character); + } + else if (builder.Length > 0 && builder[builder.Length - 1] != '_') + { + builder.Append('_'); + } + } + + string sanitized = builder.ToString().Trim('_', '.', '-'); + if (sanitized.Length == 0) + { + return null; + } + + char first = sanitized[0]; + if (!((first >= 'a' && first <= 'z') || (first >= 'A' && first <= 'Z') || first == '_')) + { + sanitized = "key" + sanitized; + } + + if (sanitized.Length > ControlMonitorRules.MaxContentKeyLength) + { + sanitized = sanitized.Substring(0, ControlMonitorRules.MaxContentKeyLength); + } + + return sanitized; + } + + private void Report(string message, Exception exception) + { + EventHandler handler = StatusChanged; + if (handler != null) + { + handler(this, new ControlMonitorStatusEventArgs(message, exception)); + } + } + } +} diff --git a/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs b/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs new file mode 100644 index 0000000..6f5805d --- /dev/null +++ b/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs @@ -0,0 +1,276 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using pacs_win_uia.Models; + +namespace pacs_win_uia.UI +{ + /// What the tree search is looking for. All filled fields must match (AND). + public sealed class TreeSearchCriteria + { + public string Any { get; set; } + + public string Name { get; set; } + + public string Path { get; set; } + + public string AutomationId { get; set; } + + public string ClassName { get; set; } + + public string ControlType { get; set; } + + public bool OnlyFocused { get; set; } + + public bool IsEmpty + { + get + { + return string.IsNullOrWhiteSpace(Any) && string.IsNullOrWhiteSpace(Name) && + string.IsNullOrWhiteSpace(Path) && string.IsNullOrWhiteSpace(AutomationId) && + string.IsNullOrWhiteSpace(ClassName) && string.IsNullOrWhiteSpace(ControlType) && + !OnlyFocused; + } + } + + /// 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) + { + if (node == null) + { + return false; + } + + if (OnlyFocused && !focused) + { + return false; + } + + if (!MatchesAny(Any, node, path)) + { + return false; + } + + if (!MatchesField(Name, node.Uia == null ? null : node.Uia.Name, + node.Msaa == null ? null : node.Msaa.Name, node.Window == null ? null : node.Window.Title)) + { + return false; + } + + return MatchesField(Path, path, null, null) && + MatchesField(AutomationId, node.Uia == null ? null : node.Uia.AutomationId, null, null) && + MatchesField(ClassName, node.Uia == null ? null : node.Uia.ClassName, + null, node.Window == null ? null : node.Window.ClassName) && + MatchesField(ControlType, node.Uia == null ? null : node.Uia.ControlType, + node.Msaa == null ? null : node.Msaa.RoleText, null); + } + + /// The simple box matches any of the identifying fields. + private static bool MatchesAny(string filter, ControlTreeNode node, string path) + { + if (string.IsNullOrWhiteSpace(filter)) + { + return true; + } + + return Contains(node.Uia == null ? null : node.Uia.Name, filter) + || Contains(node.Uia == null ? null : node.Uia.AutomationId, filter) + || Contains(node.Uia == null ? null : node.Uia.ClassName, filter) + || Contains(node.Uia == null ? null : node.Uia.ControlType, filter) + || Contains(node.Msaa == null ? null : node.Msaa.Name, filter) + || Contains(node.Msaa == null ? null : node.Msaa.RoleText, filter) + || Contains(node.Window == null ? null : node.Window.Title, filter) + || Contains(node.Window == null ? null : node.Window.ClassName, filter) + || Contains(path, filter); + } + + private static bool MatchesField(string filter, string first, string second, string third) + { + if (string.IsNullOrWhiteSpace(filter)) + { + return true; + } + + return Contains(first, filter) || Contains(second, filter) || Contains(third, filter); + } + + private static bool Contains(string value, string filter) + { + return !string.IsNullOrEmpty(value) && + value.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0; + } + } + + /// + /// Control-tree search bar: one box by default, with a "更多" panel for the detailed fields. + /// It only collects criteria; walking and filtering the tree stays in MainForm, which owns it. + /// + 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 TextBox _nameBox; + private readonly TextBox _pathBox; + 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; + + public ControlTreeSearchPanel() + { + Height = 28; + + var bar = new FlowLayoutPanel + { + Dock = DockStyle.Top, + Height = 28, + WrapContents = false, + FlowDirection = FlowDirection.LeftToRight + }; + + bar.Controls.Add(new Label { Text = "搜索", AutoSize = true, Padding = new Padding(2, 6, 0, 0) }); + _anyBox = new TextBox { Width = 180 }; + _anyBox.TextChanged += delegate { RaiseSearchChanged(); }; + bar.Controls.Add(_anyBox); + _onlyMatches = new CheckBox { Text = "仅显示匹配", AutoSize = true, Padding = new Padding(4, 6, 0, 0) }; + _onlyMatches.CheckedChanged += delegate { RaiseSearchChanged(); }; + bar.Controls.Add(_onlyMatches); + _previous = new Button { Text = "▲", AutoSize = true }; + _previous.Click += delegate { RaiseNavigate(-1); }; + _next = new Button { Text = "▼", AutoSize = true }; + _next.Click += delegate { RaiseNavigate(1); }; + bar.Controls.Add(_previous); + bar.Controls.Add(_next); + _countLabel = new Label { Text = "匹配 0 项", AutoSize = true, Padding = new Padding(4, 6, 0, 0), ForeColor = Color.DarkSlateGray }; + bar.Controls.Add(_countLabel); + _more = new Button { Text = "更多…", AutoSize = true }; + _more.Click += delegate { ToggleAdvanced(); }; + bar.Controls.Add(_more); + + _advanced = new Panel { Dock = DockStyle.Top, Height = 58, Visible = false }; + var grid = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + WrapContents = true, + FlowDirection = FlowDirection.LeftToRight, + Padding = new Padding(0, 2, 0, 0) + }; + _nameBox = AddField(grid, "名称"); + _pathBox = AddField(grid, "路径"); + _automationIdBox = AddField(grid, "AutomationId"); + _classBox = AddField(grid, "类名"); + _typeBox = AddField(grid, "类型"); + _onlyFocused = new CheckBox { Text = "仅焦点元素", AutoSize = true, Padding = new Padding(4, 6, 0, 0) }; + _onlyFocused.CheckedChanged += delegate { RaiseSearchChanged(); }; + grid.Controls.Add(_onlyFocused); + _apply = new Button { Text = "应用", AutoSize = true }; + _apply.Click += delegate { RaiseSearchChanged(); }; + grid.Controls.Add(_apply); + _clear = new Button { Text = "清除", AutoSize = true }; + _clear.Click += delegate { ClearAll(); }; + grid.Controls.Add(_clear); + + _advanced.Controls.Add(grid); + Controls.Add(_advanced); + Controls.Add(bar); + } + + /// Fires when the criteria change; the owner re-applies filtering. + public event EventHandler SearchChanged; + + /// +1 = next match, -1 = previous match. + public event EventHandler NavigateRequested; + + public TreeSearchCriteria Criteria + { + get + { + return new TreeSearchCriteria + { + Any = _anyBox.Text, + Name = _nameBox.Text, + Path = _pathBox.Text, + AutomationId = _automationIdBox.Text, + ClassName = _classBox.Text, + ControlType = _typeBox.Text, + OnlyFocused = _onlyFocused.Checked + }; + } + } + + public bool OnlyMatches + { + get { return _onlyMatches.Checked; } + } + + 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(FlowLayoutPanel parent, string label) + { + parent.Controls.Add(new Label { Text = label, AutoSize = true, Padding = new Padding(6, 6, 0, 0) }); + var box = new TextBox { Width = 110 }; + box.TextChanged += delegate { /* applied by 应用 / Enter to avoid re-filtering per key */ }; + parent.Controls.Add(box); + return box; + } + + private void ToggleAdvanced() + { + _advancedVisible = !_advancedVisible; + _advanced.Visible = _advancedVisible; + Height = _advancedVisible ? 86 : 28; + _more.Text = _advancedVisible ? "收起" : "更多…"; + RaiseSearchChanged(); + } + + private void ClearAll() + { + _anyBox.Text = string.Empty; + _nameBox.Text = string.Empty; + _pathBox.Text = string.Empty; + _automationIdBox.Text = string.Empty; + _classBox.Text = string.Empty; + _typeBox.Text = string.Empty; + _onlyFocused.Checked = false; + _onlyMatches.Checked = false; + RaiseSearchChanged(); + } + + private void RaiseSearchChanged() + { + EventHandler handler = SearchChanged; + if (handler != null) + { + handler(this, EventArgs.Empty); + } + } + + private void RaiseNavigate(int direction) + { + EventHandler handler = NavigateRequested; + if (handler != null) + { + handler(this, new FloatingActionEventArgs(direction.ToString())); + } + } + } +} diff --git a/src/pacs_win_uia/UI/FloatingToolbarForm.cs b/src/pacs_win_uia/UI/FloatingToolbarForm.cs new file mode 100644 index 0000000..ebaa11f --- /dev/null +++ b/src/pacs_win_uia/UI/FloatingToolbarForm.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using pacs_win_uia.Interop; +using pacs_win_uia.Models; + +namespace pacs_win_uia.UI +{ + public sealed class FloatingActionEventArgs : EventArgs + { + public FloatingActionEventArgs(string action) + { + Action = action; + } + + public string Action { get; private set; } + } + + /// + /// A small always-on-top toolbar that never takes focus, so it can sit next to the PACS window + /// without stealing its keyboard. It is the "方案 B" from the requirements: an independent + /// operation bar instead of injecting into the target's context menu. + /// + public sealed class FloatingToolbarForm : Form + { + /// Actions the toolbar can expose; the settings dialog edits this list. + public static readonly IList KnownActions = new List + { + "读取选中控件列表", + "定位到控件", + "读取全部监控项", + "检查选中窗口", + "拾取控件" + }; + + private readonly FloatingButtonSettings _settings; + private Point _dragOffset; + private bool _dragging; + + public FloatingToolbarForm(FloatingButtonSettings settings) + { + _settings = settings ?? new FloatingButtonSettings(); + FormBorderStyle = FormBorderStyle.None; + ShowInTaskbar = false; + StartPosition = FormStartPosition.Manual; + TopMost = true; + BackColor = Color.FromArgb(245, 245, 245); + Padding = new Padding(4); + DoubleBuffered = true; + Opacity = Math.Max(0.2D, Math.Min(1.0D, _settings.OpacityPercent / 100.0D)); + + var panel = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + WrapContents = false, + FlowDirection = FlowDirection.LeftToRight + }; + + IList actions = _settings.Actions == null || _settings.Actions.Count == 0 + ? new List(KnownActions) + : _settings.Actions; + foreach (string action in actions) + { + if (string.IsNullOrWhiteSpace(action)) + { + continue; + } + + var button = new Button + { + Text = action, + AutoSize = true, + FlatStyle = FlatStyle.System, + Margin = new Padding(2) + }; + string captured = action; + button.Click += delegate { Raise(captured); }; + panel.Controls.Add(button); + } + + var close = new Button + { + Text = "×", + AutoSize = true, + FlatStyle = FlatStyle.System, + Margin = new Padding(2) + }; + close.Click += delegate { Hide(); }; + panel.Controls.Add(close); + + Controls.Add(panel); + AutoSize = true; + AutoSizeMode = AutoSizeMode.GrowAndShrink; + + // Drag the bar by its background; the buttons still receive their own clicks. + panel.MouseDown += OnDragStart; + panel.MouseMove += OnDragMove; + panel.MouseUp += OnDragEnd; + MouseDown += OnDragStart; + MouseMove += OnDragMove; + MouseUp += OnDragEnd; + } + + public event EventHandler ActionInvoked; + + /// Remembers the position so the bar comes back where the operator left it. + public void SavePosition() + { + _settings.X = Left; + _settings.Y = Top; + } + + protected override bool ShowWithoutActivation + { + get { return true; } + } + + protected override CreateParams CreateParams + { + get + { + CreateParams parameters = base.CreateParams; + parameters.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW | NativeMethods.WS_EX_NOACTIVATE; + return parameters; + } + } + + protected override void OnShown(EventArgs e) + { + base.OnShown(e); + Point target = new Point(_settings.X, _settings.Y); + Rectangle screen = Screen.GetWorkingArea(target); + if (!screen.Contains(target)) + { + target = new Point(screen.Left + 60, screen.Top + 60); + } + + Location = target; + } + + private void OnDragStart(object sender, MouseEventArgs e) + { + if (e.Button != MouseButtons.Left) + { + return; + } + + _dragging = true; + _dragOffset = new Point(e.X, e.Y); + } + + private void OnDragMove(object sender, MouseEventArgs e) + { + if (!_dragging) + { + return; + } + + Point screenPoint = ((Control)sender).PointToScreen(new Point(e.X, e.Y)); + Location = new Point(screenPoint.X - _dragOffset.X, screenPoint.Y - _dragOffset.Y); + } + + private void OnDragEnd(object sender, MouseEventArgs e) + { + if (!_dragging) + { + return; + } + + _dragging = false; + SavePosition(); + } + + private void Raise(string action) + { + EventHandler handler = ActionInvoked; + if (handler != null) + { + handler(this, new FloatingActionEventArgs(action)); + } + } + } +} diff --git a/src/pacs_win_uia/UI/HighlightOverlayForm.cs b/src/pacs_win_uia/UI/HighlightOverlayForm.cs new file mode 100644 index 0000000..a8e8fa5 --- /dev/null +++ b/src/pacs_win_uia/UI/HighlightOverlayForm.cs @@ -0,0 +1,102 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using pacs_win_uia.Interop; + +namespace pacs_win_uia.UI +{ + /// + /// A non-activating, click-through highlight rectangle. + /// + public sealed class HighlightOverlayForm : Form + { + public HighlightOverlayForm() + { + FormBorderStyle = FormBorderStyle.None; + ShowInTaskbar = false; + StartPosition = FormStartPosition.Manual; + TopMost = true; + BackColor = Color.Magenta; + TransparencyKey = Color.Magenta; + Opacity = 0.85D; + } + + protected override bool ShowWithoutActivation + { + get { return true; } + } + + protected override CreateParams CreateParams + { + get + { + CreateParams parameters = base.CreateParams; + parameters.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW | + NativeMethods.WS_EX_NOACTIVATE | + NativeMethods.WS_EX_TRANSPARENT; + return parameters; + } + } + + protected override void WndProc(ref Message message) + { + if (message.Msg == NativeMethods.WM_NCHITTEST) + { + message.Result = new IntPtr(NativeMethods.HTTRANSPARENT); + return; + } + + if (message.Msg == NativeMethods.WM_MOUSEACTIVATE) + { + message.Result = new IntPtr(NativeMethods.MA_NOACTIVATE); + return; + } + + base.WndProc(ref message); + } + + public void ShowHighlight(Rectangle bounds) + { + if (bounds.Width < 1 || bounds.Height < 1) + { + Hide(); + return; + } + + Bounds = bounds; + if (!Visible) + { + Show(); + } + + Invalidate(); + } + + public void HideHighlight() + { + Hide(); + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + e.Graphics.SmoothingMode = SmoothingMode.None; + using (var pen = new Pen(Color.Red, 3F)) + { + Rectangle border = new Rectangle(1, 1, Math.Max(0, ClientSize.Width - 3), Math.Max(0, ClientSize.Height - 3)); + e.Graphics.DrawRectangle(pen, border); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + HideHighlight(); + } + + base.Dispose(disposing); + } + } +} diff --git a/src/pacs_win_uia/UI/MainForm.cs b/src/pacs_win_uia/UI/MainForm.cs new file mode 100644 index 0000000..48fffb1 --- /dev/null +++ b/src/pacs_win_uia/UI/MainForm.cs @@ -0,0 +1,2362 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Windows.Automation; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Interop; +using pacs_win_uia.Picker; +using pacs_win_uia.Models; +using pacs_win_uia.Services; +using pacs_win_uia.UI; + +namespace pacs_win_uia +{ + /// + /// First-stage shell: window discovery, read-only UIA inspection and tree export. + /// + 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; + private readonly UiAutomationService _uiAutomationService; + private readonly ControlTreeExporter _treeExporter; + private readonly ListView _windowList; + private readonly TextBox _windowSearchBox; + private readonly Label _windowCountLabel; + private readonly TreeView _controlTree; + private readonly DataGridView _listResultGrid; + private readonly TabControl _resultTabs; + private readonly DataTable _listResultTable; + private readonly TabPage _listResultTab; + private readonly TabPage _controlTreeTab; + private readonly PropertyGrid _propertyGrid; + private readonly ControlTreeService _controlTreeService; + private readonly AccessibilityActivationService _activationService; + private readonly ControlMonitorEditorControl _monitorEditor; + private readonly TextBox _statusText; + private readonly Button _refreshButton; + private readonly Button _inspectButton; + private readonly Button _exportButton; + private readonly Button _readListButton; + private readonly Button _exportListButton; + private readonly Button _pickButton; + 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 Services.AppSettingsStore _settingsStore; + private readonly Services.CommandRunner _commandRunner; + private readonly HighlightOverlayForm _locateHighlight; + private AppSettings _settings; + private FloatingToolbarForm _floatingToolbar; + private readonly List _treeMatches = new List(); + private readonly Button _activateButton; + private readonly Label _pickerPreviewLabel; + private readonly TargetProbeService _probeService; + private readonly ListReaderService _listReaderService; + private readonly ListResultExporter _listResultExporter; + private readonly CrosshairPicker _picker; + private readonly System.Windows.Forms.Timer _autoInspectTimer; + private readonly System.Windows.Forms.Timer _treeReadTimer; + private DateTime _treeReadStartedUtc; + private string _treeReadLabel; + 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; + private ControlTreeNode _currentTree; + private ControlTreeNode _currentTreeRoot; + private IntPtr _treeRootHandle = IntPtr.Zero; + private ControlTreeSource? _currentTreeSource; + private AutomationElement _treeUiaRoot; + private NativeWindowInfo _treeWindow; + private UiaElementInfo _currentElement; + private NativeWindowInfo _inspectedWindow; + private IList _windows = new List(); + private int _inspectionSequence; + private int _pickSession; + private int _activeReads; + private bool _suppressSelectionEvents; + private IntPtr _lastAutoInspectedHandle = IntPtr.Zero; + private IntPtr _foregroundBeforePick = IntPtr.Zero; + private string _lastListReadElement = "(无)"; + + public MainForm() + { + _windowService = new NativeWindowService(); + _uiAutomationService = new UiAutomationService(); + _treeExporter = new ControlTreeExporter(); + _listReaderService = new ListReaderService(); + _listResultExporter = new ListResultExporter(); + _controlTreeService = new ControlTreeService(); + _settingsStore = new Services.AppSettingsStore(); + _settings = _settingsStore.Load(); + _commandRunner = new Services.CommandRunner(); + _commandRunner.Output += delegate(object sender, CommandOutputEventArgs e) + { + AppLog.Info("命令输出[" + e.Name + "]" + (e.IsError ? "(stderr) " : " ") + e.Text); + }; + _activationService = new AccessibilityActivationService(); + _probeService = new TargetProbeService( + _windowService, + _uiAutomationService, + Process.GetCurrentProcess().Id); + _picker = new CrosshairPicker(this, _probeService); + _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 }; + _treeReadTimer.Tick += TreeReadTimerOnTick; + + Text = "PACS Windows UI Automation Inspector - 第一/二阶段"; + StartPosition = FormStartPosition.CenterScreen; + MinimumSize = new Size(900, 600); + Size = PreferredWindowSize; + + var toolbar = new FlowLayoutPanel + { + Dock = DockStyle.Top, + Height = 42, + Padding = new Padding(6), + WrapContents = false + }; + + _refreshButton = new Button { Text = "刷新窗口", AutoSize = true }; + _pickButton = new Button { Text = "拾取控件", AutoSize = true, Enabled = true }; + _inspectButton = new Button { Text = "检查选中窗口", AutoSize = true, Enabled = false }; + _readListButton = new Button { Text = "读取选中控件列表", AutoSize = true, Enabled = false }; + _exportButton = new Button { Text = "导出控件树", AutoSize = true, Enabled = false }; + _exportListButton = new Button { Text = "导出列表 JSON/CSV", AutoSize = true, Enabled = false }; + _treeSourceCombo = new ComboBox + { + DropDownStyle = ComboBoxStyle.DropDownList, + Width = 190 + }; + _treeSourceCombo.Items.AddRange(new object[] + { + "自动(UIA → MSAA → Win32)", + "UIA", + "MSAA", + "Win32" + }); + _treeSourceCombo.SelectedIndex = 0; + _activateButton = new Button + { + Text = "尝试激活目标无障碍", + AutoSize = true, + Enabled = false + }; + _settingsButton = new Button { Text = "设置", AutoSize = true }; + _pickerPreviewLabel = new Label + { + Text = "拾取器未启动", + AutoSize = true, + Padding = new Padding(12, 7, 0, 0), + ForeColor = Color.DarkSlateGray + }; + var limitationLabel = new Label + { + Text = "只读;拾取时主界面会隐藏。页面监控和截图尚未实现。", + AutoSize = true, + Padding = new Padding(12, 7, 0, 0), + ForeColor = Color.DarkSlateGray + }; + toolbar.Controls.Add(_refreshButton); + toolbar.Controls.Add(_pickButton); + toolbar.Controls.Add(_inspectButton); + toolbar.Controls.Add(_readListButton); + toolbar.Controls.Add(_exportButton); + toolbar.Controls.Add(_exportListButton); + toolbar.Controls.Add(new Label { Text = "控件树来源:", AutoSize = true, Padding = new Padding(10, 7, 0, 0) }); + toolbar.Controls.Add(_treeSourceCombo); + toolbar.Controls.Add(_activateButton); + toolbar.Controls.Add(_settingsButton); + toolbar.Controls.Add(_pickerPreviewLabel); + toolbar.Controls.Add(limitationLabel); + + _windowSearchBox = new TextBox { Dock = DockStyle.Top }; + _windowCountLabel = new Label + { + Dock = DockStyle.Top, + Height = 20, + Text = "显示 0 / 0", + ForeColor = Color.DarkSlateGray + }; + _windowList = new ListView + { + Dock = DockStyle.Fill, + View = View.Details, + FullRowSelect = true, + HideSelection = false, + MultiSelect = false + }; + _windowList.Columns.Add("标题", 260); + _windowList.Columns.Add("进程", 130); + _windowList.Columns.Add("PID", 70); + _windowList.Columns.Add("HWND", 120); + _windowList.Columns.Add("类名", 160); + _windowList.Columns.Add("可见", 60); + _windowList.Columns.Add("最小化", 70); + + _controlTree = new TreeView { Dock = DockStyle.Fill, HideSelection = false }; + _listResultGrid = new DataGridView + { + Dock = DockStyle.Fill, + ReadOnly = true, + AllowUserToAddRows = false, + AllowUserToDeleteRows = false, + AutoGenerateColumns = true, + AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells + }; + _listResultTable = new DataTable(); + _resultTabs = new TabControl { Dock = DockStyle.Fill }; + _listResultHint = new Label + { + Dock = DockStyle.Top, + Height = 48, + Padding = new Padding(4), + ForeColor = Color.DarkSlateGray, + Text = "还没有读取。选中控件后点「读取选中控件列表」。" + }; + _listResultTab = new TabPage("列表结果"); + _listResultTab.Controls.Add(_listResultGrid); + _listResultTab.Controls.Add(_listResultHint); + _treeSearchPanel = new ControlTreeSearchPanel { Dock = DockStyle.Top }; + _controlTreeTab = new TabPage("控件树"); + _controlTreeTab.Controls.Add(_controlTree); + _controlTreeTab.Controls.Add(_treeSearchPanel); + _resultTabs.TabPages.Add(_controlTreeTab); + _resultTabs.TabPages.Add(_listResultTab); + _propertyGrid = new PropertyGrid { Dock = DockStyle.Fill, HelpVisible = true, ToolbarVisible = false }; + _monitorEditor = new ControlMonitorEditorControl(); + _monitorEditor.StatusChanged += MonitorEditorOnStatusChanged; + _monitorEditor.ControlLocated += MonitorEditorOnControlLocated; + _monitorEditor.DefinitionSelected += MonitorEditorOnDefinitionSelected; + _locateHighlight = new HighlightOverlayForm(); + _statusText = new TextBox + { + Dock = DockStyle.Bottom, + Height = 54, + Multiline = true, + ReadOnly = true, + ScrollBars = ScrollBars.Vertical + }; + + var searchPanel = new Panel { Dock = DockStyle.Top, Height = 46 }; + var searchLabel = new Label { Dock = DockStyle.Left, Width = 34, Text = "搜索", TextAlign = ContentAlignment.MiddleLeft }; + _windowCountLabel.Dock = DockStyle.Bottom; + searchPanel.Controls.Add(_windowSearchBox); + searchPanel.Controls.Add(searchLabel); + searchPanel.Controls.Add(_windowCountLabel); + _windowSearchBox.Dock = DockStyle.Fill; + + _windowListCaption = CreateCaption("窗口列表"); + var leftPanel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(6) }; + leftPanel.Controls.Add(_windowList); + leftPanel.Controls.Add(searchPanel); + leftPanel.Controls.Add(_windowListCaption); + + var centerPanel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(6) }; + centerPanel.Controls.Add(_resultTabs); + + var propertyHost = new ScrollHostPanel { Dock = DockStyle.Fill, MinimumContentWidth = 360 }; + propertyHost.Content = _propertyGrid; + _propertyCaption = CreateCaption("控件属性 —— 选中控件树的节点、或选中下面监控列表的一行,都在这里查看/编辑"); + var propertyPanel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(6) }; + propertyPanel.Controls.Add(propertyHost); + propertyPanel.Controls.Add(_propertyCaption); + + _monitorCaption = CreateCaption("控件监控列表 —— 保存后可用无界面模式(--read-saved)批量读取"); + var monitorPanel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(6) }; + // Without an explicit Dock the UserControl keeps its default 150x150 size, which is + // exactly the "控件监控列表特别小、列显示不全" bug. + _monitorEditor.Dock = DockStyle.Fill; + monitorPanel.Controls.Add(_monitorEditor); + monitorPanel.Controls.Add(_monitorCaption); + + // 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. + _splitRightColumn = new SplitContainer + { + Dock = DockStyle.Fill, + Orientation = Orientation.Horizontal + }; + _splitRightColumn.Panel1.Controls.Add(propertyPanel); + _splitRightColumn.Panel2.Controls.Add(monitorPanel); + + _splitRight = new SplitContainer + { + Dock = DockStyle.Fill, + Orientation = Orientation.Vertical + }; + _splitRight.Panel1.Controls.Add(centerPanel); + _splitRight.Panel2.Controls.Add(_splitRightColumn); + + _splitMain = new SplitContainer + { + Dock = DockStyle.Fill, + Orientation = Orientation.Vertical + }; + _splitMain.Panel1.Controls.Add(leftPanel); + _splitMain.Panel2.Controls.Add(_splitRight); + + Controls.Add(_splitMain); + Controls.Add(_statusText); + Controls.Add(toolbar); + + _refreshButton.Click += delegate { RefreshWindows(); }; + _pickButton.Click += delegate { StartPicker(); }; + _inspectButton.Click += delegate { InspectSelectedWindow(); }; + _readListButton.Click += delegate { ReadSelectedList(); }; + _exportButton.Click += delegate { ExportCurrentTree(); }; + _exportListButton.Click += delegate { ExportLastListResult(); }; + _treeSourceCombo.SelectedIndexChanged += delegate { RereadCurrentTree("来源已切换"); }; + _treeSearchPanel.SearchChanged += delegate { RebuildTreeView(); }; + _treeSearchPanel.NavigateRequested += delegate(object sender, FloatingActionEventArgs e) + { + int direction; + if (int.TryParse(e.Action, out direction)) + { + NavigateTreeMatch(direction); + } + }; + _activateButton.Click += delegate { ActivateTargetAccessibility(); }; + _settingsButton.Click += delegate { ShowSettings(); }; + _windowSearchBox.TextChanged += delegate { ApplyWindowFilter(); }; + _windowList.SelectedIndexChanged += WindowListOnSelectedIndexChanged; + _controlTree.AfterSelect += ControlTreeOnAfterSelect; + FormClosing += MainFormOnFormClosing; + Load += MainFormOnLoad; + Shown += MainFormOnShown; + } + + /// Opens the settings dialog and applies whatever was saved. + private void ShowSettings() + { + using (var dialog = new SettingsForm(_settings, _settingsStore, _commandRunner)) + { + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + } + + _settings = _settingsStore.Load(); + ApplyFloatingToolbar(); + _commandRunner.RunStartCommands(_settings); + SetStatus("设置已保存并生效:" + _settingsStore.FilePath, null); + } + + /// Shows/hides the floating bar according to the current settings. + private void ApplyFloatingToolbar() + { + if (_settings.FloatingButton.Enabled) + { + if (_floatingToolbar == null) + { + _floatingToolbar = new FloatingToolbarForm(_settings.FloatingButton); + _floatingToolbar.ActionInvoked += FloatingToolbarOnActionInvoked; + } + + _floatingToolbar.Show(); + _floatingToolbar.BringToFront(); + return; + } + + if (_floatingToolbar != null) + { + _floatingToolbar.Hide(); + } + } + + private void FloatingToolbarOnActionInvoked(object sender, FloatingActionEventArgs e) + { + switch (e.Action) + { + case "读取选中控件列表": + ReadSelectedList(); + break; + case "定位到控件": + _monitorEditor.LocateCurrentDefinition(); + break; + case "读取全部监控项": + _monitorEditor.RefreshAllStates(); + break; + case "检查选中窗口": + InspectSelectedWindow(); + break; + case "拾取控件": + StartPicker(); + break; + default: + AppLog.Warn("悬浮按钮的未知动作:" + e.Action); + break; + } + } + + private void MainFormOnLoad(object sender, EventArgs e) + { + ApplyScreenFitting(); + AppLog.Info("设置:" + _settingsStore.FilePath + + ";树深度 " + _settings.Ui.TreeMaxDepth + ",节点上限 " + _settings.Ui.TreeMaxNodes + + ",超时 " + _settings.Ui.TreeTimeoutSeconds + " 秒"); + ApplyFloatingToolbar(); + _commandRunner.RunStartCommands(_settings); + } + + /// + /// A control that was built but never added to a container is invisible on screen with no + /// error anywhere — that is how the 控件树 tab went missing once. Check it explicitly. + /// + private void VerifyLayout() + { + var required = new List + { + new LayoutRegion("窗口列表", _windowList, 200, 200), + new LayoutRegion("窗口搜索框", _windowSearchBox, 120, 20), + new LayoutRegion("结果标签页(控件树/列表结果)", _resultTabs, 200, 200), + new LayoutRegion("控件树", _controlTree, 200, 200), + new LayoutRegion("列表结果表格", _listResultGrid, 60, 60), + new LayoutRegion("属性网格", _propertyGrid, 200, 120), + new LayoutRegion("控件监控列表", _monitorEditor, 200, 150), + new LayoutRegion("状态栏", _statusText, 200, 30), + new LayoutRegion("主分隔条", _splitMain, 200, 200), + new LayoutRegion("中/右分隔条", _splitRight, 200, 200), + new LayoutRegion("属性/监控分隔条", _splitRightColumn, 200, 200), + new LayoutRegion("窗口列表标题", _windowListCaption, 200, 18), + new LayoutRegion("控件属性标题", _propertyCaption, 200, 18), + new LayoutRegion("监控列表标题", _monitorCaption, 200, 18) + }; + + int missing = 0; + foreach (LayoutRegion region in required) + { + if (region.Control == null) + { + AppLog.Error("界面布局错误:" + region.Name + " 未创建。"); + missing++; + continue; + } + + if (!IsInVisualTree(region.Control)) + { + AppLog.Error("界面布局错误:" + region.Name + " 没有被加入窗体,界面上不会显示。"); + missing++; + continue; + } + + // "Present but still its default 150x150 box" passes a parenting check, so the size + // is checked too — that is exactly what hid the too-small 控件监控列表. + Size size = region.Control.Size; + AppLog.Debug("界面区域:" + region.Name + " = " + size.Width + "x" + size.Height + + "(位置 " + region.Control.Left + "," + region.Control.Top + ")"); + if (size.Width < region.MinimumWidth || size.Height < region.MinimumHeight) + { + AppLog.Error("界面布局错误:" + region.Name + " 只有 " + size.Width + "x" + size.Height + + "(应至少 " + region.MinimumWidth + "x" + region.MinimumHeight + + "),可能没有设置 Dock/Anchor,界面上会显示不全。"); + missing++; + } + } + + AppLog.Info("界面布局检查完成:控件树节点 " + CountControls(this) + " 个,异常区域 " + missing + " 个。"); + } + + private struct LayoutRegion + { + internal LayoutRegion(string name, Control control, int minimumWidth, int minimumHeight) + { + Name = name; + Control = control; + MinimumWidth = minimumWidth; + MinimumHeight = minimumHeight; + } + + internal readonly string Name; + internal readonly Control Control; + internal readonly int MinimumWidth; + internal readonly int MinimumHeight; + } + + private bool IsInVisualTree(Control control) + { + Control current = control; + while (current != null) + { + if (ReferenceEquals(current, this)) + { + return true; + } + + current = current.Parent; + } + + return false; + } + + private static int CountControls(Control parent) + { + int count = 1; + foreach (Control child in parent.Controls) + { + count += CountControls(child); + } + + return count; + } + + private void MainFormOnShown(object sender, EventArgs e) + { + // The splitter distances depend on the final, possibly maximized, layout. + if (!_splittersInitialized) + { + _splittersInitialized = true; + ApplyInitialSplitterDistances(); + VerifyLayout(); + } + + RefreshWindows(); + } + + /// + /// Sizes the window to the screen: it used to open larger than the screen on small displays + /// (right-hand panels unreachable) and much too small on large ones (every panel cramped). + /// + /// + /// A thin title bar for each area: "属性网格"/"控件监控列表" and friends are otherwise only + /// recognisable by their content. + /// + private static Label CreateCaption(string text) + { + return new Label + { + Dock = DockStyle.Top, + Height = 22, + Text = " " + text, + TextAlign = ContentAlignment.MiddleLeft, + Font = new Font(SystemFonts.DefaultFont, FontStyle.Bold), + BackColor = Color.FromArgb(238, 238, 238), + ForeColor = Color.FromArgb(40, 40, 40) + }; + } + + private void ApplyScreenFitting() + { + Rectangle workingArea = Screen.FromControl(this).WorkingArea; + int width = Math.Min(workingArea.Width - ScreenMargin, Math.Max(MinimumSize.Width, (int)(workingArea.Width * 0.80D))); + int height = Math.Min(workingArea.Height - ScreenMargin, Math.Max(MinimumSize.Height, (int)(workingArea.Height * 0.85D))); + Size = new Size(width, height); + Location = new Point( + workingArea.Left + Math.Max(0, (workingArea.Width - width) / 2), + workingArea.Top + Math.Max(0, (workingArea.Height - height) / 2)); + AppLog.Info("屏幕工作区:" + workingArea.Width + "x" + workingArea.Height + + ";主界面尺寸:" + width + "x" + height); + } + + /// + /// SplitterDistance is validated against the panel min sizes on every assignment, so the + /// minimums are relaxed first, the distance is set, and only then are the minimums tightened. + /// + private void ApplyInitialSplitterDistances() + { + ApplySplitterLayout(_splitMain, Orientation.Vertical, 0.24D, 240, 620, "窗口列表/其余"); + ApplySplitterLayout(_splitRight, Orientation.Vertical, 0.48D, 320, 380, "控件树/右侧"); + ApplySplitterLayout(_splitRightColumn, Orientation.Horizontal, 0.52D, 160, 200, "属性/监控列表"); + } + + private static void ApplySplitterLayout( + SplitContainer container, + Orientation orientation, + double ratio, + int panel1Minimum, + int panel2Minimum, + string label) + { + int extent = orientation == Orientation.Vertical ? container.Width : container.Height; + if (extent <= 0) + { + return; + } + + try + { + int splitter = container.SplitterWidth; + int room = Math.Max(0, extent - splitter - 1); + container.Panel1MinSize = 0; + container.Panel2MinSize = 0; + + int distance = (int)(extent * ratio); + distance = Math.Max(0, Math.Min(distance, room)); + container.SplitterDistance = distance; + + container.Panel1MinSize = Math.Min(panel1Minimum, distance); + container.Panel2MinSize = Math.Min(panel2Minimum, Math.Max(0, room - distance)); + AppLog.Debug("分隔条(" + label + "):范围 " + extent + ",位置 " + container.SplitterDistance + + ",最小 " + container.Panel1MinSize + "/" + container.Panel2MinSize); + } + catch (Exception ex) + { + AppLog.Warn("设置分隔条(" + label + ")位置失败。", ex); + } + } + + // ------------------------------------------------------------------ window list + + private void RefreshWindows() + { + try + { + Stopwatch stopwatch = Stopwatch.StartNew(); + WindowEnumerationResult enumeration = _windowService.EnumerateTopLevelWindowsResult(false); + _windows = enumeration.Windows + .Where(window => window.Handle != IntPtr.Zero) + .ToList(); + stopwatch.Stop(); + AppLog.Info("窗口枚举完成:可见顶级窗口 " + _windows.Count + " 个,耗时 " + stopwatch.ElapsedMilliseconds + " ms。"); + ApplyWindowFilter(); + _pickButton.Enabled = !_picker.IsPicking; + SetStatus(enumeration.Succeeded + ? "已枚举 " + _windows.Count + " 个可见顶层窗口。" + : "窗口枚举不完整:" + enumeration.Error + ";已获取 " + _windows.Count + " 个窗口。", null); + } + catch (Exception ex) + { + AppLog.Error("窗口枚举失败。", ex); + SetStatus("窗口枚举失败。", ex); + } + } + + /// + /// Rebuilds the window list: valuable windows first, then a separator group, filtered by the + /// search box. Selection is restored by HWND and never triggers an automatic tree read. + /// + private void ApplyWindowFilter() + { + NativeWindowInfo previousSelection = GetSelectedWindow(); + string filter = _windowSearchBox.Text.Trim(); + bool suppress = _suppressSelectionEvents; + _suppressSelectionEvents = true; + _windowList.BeginUpdate(); + try + { + _windowList.Items.Clear(); + _windowList.Groups.Clear(); + var primaryGroup = new ListViewGroup("主要窗口(有标题且可见)"); + var otherGroup = new ListViewGroup("其他窗口(无标题 / 隐藏)"); + _windowList.Groups.Add(primaryGroup); + _windowList.Groups.Add(otherGroup); + + IntPtr foreground = _settings != null && _settings.Ui.HighlightForegroundWindow + ? NativeMethods.GetForegroundWindow() + : IntPtr.Zero; + int shown = 0; + foreach (NativeWindowInfo window in _windows) + { + if (!MatchesFilter(window, filter)) + { + continue; + } + + ListViewItem item = CreateWindowItem(window); + item.Group = IsPrimaryWindow(window) ? primaryGroup : otherGroup; + if (foreground != IntPtr.Zero && window.Handle == foreground) + { + // The window the user is actually looking at. + item.BackColor = Color.FromArgb(255, 250, 205); + item.ToolTipText = "当前前台窗口(屏幕上最上方的那个)"; + } + else if (window.IsMinimized) + { + item.ForeColor = Color.Gray; + } + + _windowList.Items.Add(item); + shown++; + } + + if (primaryGroup.Items.Count == 0) + { + _windowList.Groups.Remove(primaryGroup); + } + + if (otherGroup.Items.Count == 0) + { + _windowList.Groups.Remove(otherGroup); + } + + _windowCountLabel.Text = "显示 " + shown + " / " + _windows.Count + "(按标题、进程名或 PID 过滤)"; + if (previousSelection != null) + { + SelectWindowItem(previousSelection.Handle); + } + } + finally + { + _windowList.EndUpdate(); + _suppressSelectionEvents = suppress; + } + } + + private static ListViewItem CreateWindowItem(NativeWindowInfo window) + { + var item = new ListViewItem(window.Title ?? string.Empty); + item.SubItems.Add(window.ProcessName ?? string.Empty); + item.SubItems.Add(window.ProcessId.ToString()); + item.SubItems.Add(window.HwndHex); + item.SubItems.Add(window.ClassName ?? string.Empty); + item.SubItems.Add(window.IsVisible ? "是" : "否"); + item.SubItems.Add(window.IsMinimized ? "是" : "否"); + item.Tag = window; + return item; + } + + /// A window worth showing first: it has a title and the user can see it. + private static bool IsPrimaryWindow(NativeWindowInfo window) + { + return window.IsVisible && !string.IsNullOrWhiteSpace(window.Title); + } + + private static bool MatchesFilter(NativeWindowInfo window, string filter) + { + if (string.IsNullOrEmpty(filter)) + { + return true; + } + + if (!string.IsNullOrEmpty(window.Title) && + window.Title.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0) + { + return true; + } + + if (window.ProcessId.ToString().IndexOf(filter, StringComparison.Ordinal) >= 0) + { + return true; + } + + return !string.IsNullOrEmpty(window.ProcessName) && + window.ProcessName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0; + } + + private bool SelectWindowItem(IntPtr handle) + { + if (handle == IntPtr.Zero) + { + return false; + } + + bool suppress = _suppressSelectionEvents; + _suppressSelectionEvents = true; + try + { + _windowList.SelectedItems.Clear(); + foreach (ListViewItem item in _windowList.Items) + { + var window = item.Tag as NativeWindowInfo; + if (window == null || window.Handle != handle) + { + continue; + } + + item.Selected = true; + item.EnsureVisible(); + return true; + } + } + finally + { + _suppressSelectionEvents = suppress; + } + + return false; + } + + /// + /// Selects the row for a picked target. A pick often lands on a child window + /// (a renderer/browser host), which has no row of its own, so the row is matched by the + /// top-level window first and by process as a last resort. + /// + private bool SelectWindowItem(NativeWindowInfo picked) + { + if (picked == null) + { + return false; + } + + if (SelectWindowItem(picked.Handle)) + { + return true; + } + + bool suppress = _suppressSelectionEvents; + _suppressSelectionEvents = true; + try + { + _windowList.SelectedItems.Clear(); + ListViewItem sameProcess = null; + foreach (ListViewItem item in _windowList.Items) + { + var window = item.Tag as NativeWindowInfo; + if (window == null) + { + continue; + } + + if (!string.IsNullOrEmpty(picked.RootHwndHex) && + string.Equals(window.HwndHex, picked.RootHwndHex, StringComparison.Ordinal)) + { + item.Selected = true; + item.EnsureVisible(); + AppLog.Info("已按顶层窗口 " + picked.RootHwndHex + " 同步选中窗口列表。"); + return true; + } + + if (sameProcess == null && window.ProcessId == picked.ProcessId) + { + sameProcess = item; + } + } + + if (sameProcess != null) + { + sameProcess.Selected = true; + sameProcess.EnsureVisible(); + AppLog.Info("已按进程 " + picked.ProcessId + " 同步选中窗口列表。"); + return true; + } + } + finally + { + _suppressSelectionEvents = suppress; + } + + AppLog.Warn("窗口列表里没有与拾取目标(" + picked + ")匹配的顶层窗口,未同步选中。"); + return false; + } + + private void WindowListOnSelectedIndexChanged(object sender, EventArgs e) + { + bool hasSelection = _windowList.SelectedItems.Count > 0; + _inspectButton.Enabled = hasSelection; + _pickButton.Enabled = !_picker.IsPicking; + if (!hasSelection) + { + ClearInspectionState(); + return; + } + + if (_suppressSelectionEvents) + { + return; + } + + NativeWindowInfo window = GetSelectedWindow(); + ClearInspectionState(); + _propertyGrid.SelectedObject = window; + _currentElement = null; + _activateButton.Enabled = window != null; + ShowNodeProperties(null); + if (window == null) + { + return; + } + + // Debounced: holding an arrow key must not queue one tree read per window. + if (_settings != null && !_settings.Ui.AutoReadTreeOnSelect) + { + SetStatus("已选中窗口。按设置未自动读取控件树,可点「检查选中窗口」。", null); + return; + } + + _autoInspectTimer.Stop(); + _autoInspectTimer.Start(); + } + + /// Keeps the status line honest while a tree read is still running. + private void TreeReadTimerOnTick(object sender, EventArgs e) + { + if (_treeReadStartedUtc == default(DateTime)) + { + return; + } + + double seconds = (DateTime.UtcNow - _treeReadStartedUtc).TotalSeconds; + SetStatus(string.Format("正在读取控件树…已 {0:0.0} 秒({1})。目标复杂或 Provider 无响应时会比较慢。", + seconds, _treeReadLabel), null); + } + + private void AutoInspectTimerOnTick(object sender, EventArgs e) + { + _autoInspectTimer.Stop(); + if (_suppressSelectionEvents || _picker.IsPicking) + { + return; + } + + NativeWindowInfo window = GetSelectedWindow(); + if (window == null || window.Handle == IntPtr.Zero) + { + return; + } + + if (window.Handle == _lastAutoInspectedHandle && _currentTree != null) + { + return; + } + + _lastAutoInspectedHandle = window.Handle; + InspectWindow(window); + } + + private void ClearInspectionState() + { + CancelInspection(); + _inspectionSequence++; + _currentTree = null; + _currentElement = null; + _inspectedWindow = null; + _lastListResult = null; + CancelListRead(); + ClearListResultGrid(); + _controlTree.Nodes.Clear(); + _propertyGrid.SelectedObject = null; + _exportButton.Enabled = false; + _exportListButton.Enabled = false; + _readListButton.Enabled = false; + _monitorEditor.SetCurrentNode(null, null); + ShowNodeProperties(null); + } + + // ------------------------------------------------------------------ picker + + private void StartPicker() + { + if (_picker.IsPicking) + { + _picker.Cancel(); + return; + } + + _pickButton.Enabled = false; + _pickerPreviewLabel.Text = "拾取中:移动鼠标,按住并释放左键确认,Esc 取消"; + SetStatus("十字拾取器已启动。主界面已隐藏,不会注入目标进程,也不会修改目标状态。", null); + _monitorEditor.CommitEdits(); + + // Captured before hiding so focus can be handed back to the target application. + _locateHighlight.HideHighlight(); + _foregroundBeforePick = NativeMethods.GetForegroundWindow(); + AppLog.Info("拾取开始:隐藏主界面;原前台窗口=" + NativeWindowInfo.FormatHandle(_foregroundBeforePick)); + Hide(); + try + { + _picker.Start(); + } + catch (Exception ex) + { + AppLog.Error("拾取器启动失败,已恢复主界面。", ex); + RestoreAfterPick(); + SetStatus("拾取器启动失败。", ex); + } + } + + /// + /// Single restore path for both pick outcomes. Plain Form.Show() activates the tool and + /// steals focus from the PACS client, so focus is handed back explicitly. + /// + private void RestoreAfterPick() + { + if (IsDisposed) + { + return; + } + + if (!Visible) + { + Show(); + } + + IntPtr handle = Handle; + NativeMethods.ShowWindow(handle, NativeMethods.SW_SHOWNOACTIVATE); + IntPtr previous = _foregroundBeforePick; + _foregroundBeforePick = IntPtr.Zero; + if (previous != IntPtr.Zero && previous != handle && NativeMethods.IsWindow(previous)) + { + NativeMethods.SetForegroundWindow(previous); + AppLog.Info("已把前台窗口交还给 " + NativeWindowInfo.FormatHandle(previous)); + } + } + + private void PickerOnPreviewChanged(object sender, PointPickResult result) + { + if (result == null) + { + return; + } + + string native = result.Window == null + ? "HWND 未获取" + : result.Window.HwndHex + " / " + (result.Window.Title ?? "无标题"); + string uia = result.AutomationElement == null + ? "UIA 未获取" + : result.AutomationElement.ToString(); + _pickerPreviewLabel.Text = string.Format("拾取预览:{0}; {1}; 坐标 ({2},{3})", native, uia, result.ScreenX, result.ScreenY); + } + + private void PickerOnPicked(object sender, PointPickResult result) + { + RestoreAfterPick(); + _pickButton.Enabled = true; + _pickerPreviewLabel.Text = result == null ? "拾取失败" : "已拾取目标"; + _pickSession++; + ClearInspectionState(); + _inspectionSequence++; + _inspectButton.Enabled = false; + _lastAutoInspectedHandle = IntPtr.Zero; + + if (result == null) + { + SetStatus("拾取未返回结果。", null); + return; + } + + ApplyPickResult(result); + + // Only a top-level window was reachable. Browser-based clients start their accessibility + // tree when a client first asks, so a second probe a moment later normally reaches the + // rendered control that the first probe could not see. + if (_currentElement != null && string.Equals(_currentElement.ControlType, "ControlType.Window", StringComparison.Ordinal)) + { + ScheduleDeeperPickRetry(result, _pickSession); + } + } + + /// + /// Wraps a pick result as a tree node, so "添加当前控件" works for MSAA/Win32 picks too + /// (a picked target that UIA cannot see still has to be recordable). + /// + private static ControlTreeNode BuildPickedNode(PointPickResult result) + { + if (result == null) + { + return null; + } + + if (result.AutomationElement != null && result.AutomationElement.IsAvailable) + { + return new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = result.AutomationElement }; + } + + if (result.Msaa != null) + { + return new ControlTreeNode { Source = ControlTreeSource.Msaa, Msaa = result.Msaa }; + } + + if (result.DeepestWindow != null) + { + return new ControlTreeNode { Source = ControlTreeSource.Win32, Window = result.DeepestWindow }; + } + + return null; + } + + private void ApplyPickResult(PointPickResult result) + { + _currentElement = result.AutomationElement; + _inspectedWindow = result.Window; + _propertyGrid.SelectedObject = result.AutomationElement ?? (object)result.Window; + _monitorEditor.SetCurrentNode(BuildPickedNode(result), _inspectedWindow); + ShowNodeProperties(_currentTreeRoot); + _readListButton.Enabled = _currentElement != null && _currentElement.IsAvailable; + + // Show the picked window in the list for context; this must not replace the picked + // element's tree with a whole-window tree. + RefreshWindows(); + if (result.Window != null) + { + SelectWindowItem(result.Window); + } + + if (result.IsWindowOnlyPick) + { + SetStatus("只拾取到窗口「" + (result.Window == null ? "(未知)" : result.Window.ToString()) + + "」:UIA 只返回窗口本身、MSAA 在该窗口上也没有命中内部对象," + + "窗口区域已高亮,但光标下的具体控件无法确定。" + + "可试试切换控件树来源,或点「尝试激活目标无障碍」。", null); + } + + if (_currentElement != null && _currentElement.IsAvailable && _currentElement.Element != null) + { + AutomationElement root = _currentElement.Element; + if (!result.IsWindowOnlyPick) + { + SetStatus("已拾取 UIA 元素:" + _currentElement + ";正在读取控件树……", null); + } + + BeginTreeRead( + result.Window == null ? IntPtr.Zero : result.Window.Handle, + root, + result.Window, + "被拾取控件 " + _currentElement); + return; + } + + SetStatus("已拾取窗口,但 UIA 元素不可用:" + (result.FailureReason ?? "未知原因"), null); + if (result.Window != null) + { + // Still show the window's tree so the window is not a dead end. + BeginTreeRead(result.Window.Handle, null, result.Window, result.Window.ToString()); + } + } + + /// + /// Re-probes the same screen point once, on a background thread, and adopts the result only + /// if it reaches something deeper than the window the first probe returned. + /// + private void ScheduleDeeperPickRetry(PointPickResult firstPick, int session) + { + if (firstPick == null || firstPick.Window == null) + { + return; + } + + Point screenPoint = firstPick.ScreenPoint; + IntPtr handle = firstPick.Window.Handle; + string firstRuntimeId = firstPick.AutomationElement == null ? null : firstPick.AutomationElement.RuntimeId; + AppLog.Info("拾取只拿到了顶层窗口(" + firstPick.Window + ")," + + DeeperPickRetryDelayMs + "ms 后按同一坐标重探一次,看目标是否已激活无障碍树。"); + + Task retry = Task.Factory.StartNew( + delegate + { + Thread.Sleep(DeeperPickRetryDelayMs); + return _probeService.Probe(screenPoint, handle); + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + + retry.ContinueWith( + delegate(Task completed) + { + if (completed.IsFaulted || completed.IsCanceled) + { + if (completed.IsFaulted) + { + AppLog.Warn("重探拾取目标失败。", completed.Exception.GetBaseException()); + } + + return; + } + + PointPickResult deeper = completed.Result; + bool improved = deeper != null + && deeper.AutomationElement != null + && deeper.AutomationElement.IsAvailable + && deeper.AutomationElement.Element != null + && !string.Equals(deeper.AutomationElement.ControlType, "ControlType.Window", StringComparison.Ordinal) + && !string.Equals(deeper.AutomationElement.RuntimeId, firstRuntimeId, StringComparison.Ordinal); + if (!improved) + { + AppLog.Info("重探后仍未拿到比窗口更深的元素,保留原结果。"); + return; + } + + AppLog.Info("重探到更深的控件:" + deeper.AutomationElement + ";已改用该元素。"); + if (IsDisposed || !IsHandleCreated || session != _pickSession) + { + return; + } + + try + { + BeginInvoke((Action)delegate + { + if (session != _pickSession || IsDisposed) + { + return; + } + + ApplyPickResult(deeper); + SetStatus("已拾取到更深层的控件:" + deeper.AutomationElement, null); + }); + } + catch (Exception ex) when (ex is InvalidOperationException || ex is ObjectDisposedException) + { + // The form is going away; nothing to update. + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + } + + private void PickerOnCanceled(object sender, EventArgs e) + { + RestoreAfterPick(); + _pickButton.Enabled = true; + _pickerPreviewLabel.Text = "拾取已取消"; + SetStatus("十字拾取已取消。", null); + } + + // ------------------------------------------------------------------ tree + + private void InspectSelectedWindow() + { + NativeWindowInfo window = GetSelectedWindow(); + if (window == null) + { + return; + } + + _lastAutoInspectedHandle = window.Handle; + InspectWindow(window); + } + + private void InspectWindow(NativeWindowInfo window) + { + if (window == null || window.Handle == IntPtr.Zero) + { + return; + } + + IntPtr handle = window.Handle; + _inspectButton.Enabled = false; + _exportButton.Enabled = false; + _exportListButton.Enabled = false; + _readListButton.Enabled = false; + _lastListResult = null; + CancelListRead(); + SetStatus("正在读取 UIA 控件树……", null); + BeginTreeRead(handle, null, window, window.ToString()); + } + + /// + /// Runs a tree read on a dedicated background thread: a wedged cross-process provider call + /// cannot be interrupted, and it must not consume a thread pool thread that later reads need. + /// + /// + /// Runs a tree read on a dedicated background thread: a wedged cross-process provider call + /// cannot be interrupted, and it must not consume a thread pool thread that later reads need. + /// + private void BeginTreeRead(IntPtr handle, AutomationElement uiaRoot, NativeWindowInfo window, string label) + { + if (IsDisposed || !IsHandleCreated || handle == IntPtr.Zero) + { + return; + } + + if (Interlocked.Increment(ref _activeReads) > MaxConcurrentReads) + { + Interlocked.Decrement(ref _activeReads); + AppLog.Warn("已有 " + _activeReads + " 个读取任务未返回,拒绝新的控件树读取。"); + SetStatus("上一个读取仍未返回,目标可能已无响应;请稍后再试。", null); + return; + } + + CancelInspection(); + _inspectionCancellation = CancellationTokenSource.CreateLinkedTokenSource(_shutdown.Token); + CancellationToken token = _inspectionCancellation.Token; + int sequence = ++_inspectionSequence; + ControlTreeSource? source = GetSelectedTreeSource(); + _treeRootHandle = handle; + _treeUiaRoot = uiaRoot; + _treeWindow = window; + _currentTreeSource = source; + _currentTreeRoot = null; + string sourceText = source.HasValue ? source.Value.ToString() : "自动"; + _controlTree.BeginUpdate(); + try + { + _controlTree.Nodes.Clear(); + // Without this the tree area looks like a finished (empty) result while the read runs. + _controlTree.Nodes.Add(new TreeNode("正在读取控件树…(" + sourceText + ")" + label)); + } + finally + { + _controlTree.EndUpdate(); + } + + AppLog.Info("开始读取控件树:" + label + ";来源=" + sourceText); + Stopwatch stopwatch = Stopwatch.StartNew(); + _treeReadStartedUtc = DateTime.UtcNow; + _treeReadLabel = label; + _treeReadTimer.Start(); + + var options = new ControlTreeOptions + { + MaxDepth = _settings == null ? TreeMaxDepth : _settings.Ui.TreeMaxDepth, + MaxNodes = _settings == null ? TreeMaxNodes : _settings.Ui.TreeMaxNodes, + Timeout = _settings == null ? TreeTimeout : TimeSpan.FromSeconds(_settings.Ui.TreeTimeoutSeconds) + }; + + Task task = Task.Factory.StartNew( + delegate + { + try + { + return _controlTreeService.Read(handle, uiaRoot, source, options, token); + } + catch (Exception ex) + { + AppLog.Error("控件树读取异常:" + label, ex); + return new ControlTreeResult + { + Succeeded = false, + Note = ex.GetType().Name + ": " + ex.Message, + Root = new ControlTreeNode + { + Source = ControlTreeSource.Uia, + Uia = new UiaElementInfo { IsAvailable = false, Error = ex.GetType().Name + ": " + ex.Message }, + ChildrenComplete = false, + ChildrenError = "ReadFailed" + } + }; + } + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + + task.ContinueWith( + delegate(Task completed) + { + Interlocked.Decrement(ref _activeReads); + stopwatch.Stop(); + if (IsDisposed || !IsHandleCreated || sequence != _inspectionSequence) + { + return; + } + + CancellationTokenSource inspectionCancellation = _inspectionCancellation; + if (inspectionCancellation == null || inspectionCancellation.IsCancellationRequested) + { + return; + } + + try + { + BeginInvoke((Action)delegate + { + if (sequence != _inspectionSequence || IsDisposed) + { + return; + } + + _inspectButton.Enabled = _windowList.SelectedItems.Count > 0; + _treeReadTimer.Stop(); + _treeReadStartedUtc = default(DateTime); + if (completed.IsCanceled) + { + SetStatus("控件树读取已取消。", null); + } + else if (completed.IsFaulted) + { + SetStatus("控件树读取失败。", completed.Exception.GetBaseException()); + } + else + { + AppLog.Info("控件树读取完成:" + label + ",耗时 " + stopwatch.ElapsedMilliseconds + " ms。"); + ApplyTree(completed.Result, window, label); + } + }); + } + catch (InvalidOperationException) + { + // The form handle can be destroyed between the state check and BeginInvoke during shutdown. + } + catch (Exception ex) when (ex is ObjectDisposedException) + { + // The form is already closing; no UI update is needed. + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + } + + /// Selected tree source; null means auto. + private ControlTreeSource? GetSelectedTreeSource() + { + switch (_treeSourceCombo.SelectedIndex) + { + case 1: + return ControlTreeSource.Uia; + case 2: + return ControlTreeSource.Msaa; + case 3: + return ControlTreeSource.Win32; + default: + return null; + } + } + + /// Re-reads the current root, e.g. after the source dropdown changed. + private void RereadCurrentTree(string reason) + { + if (_treeRootHandle == IntPtr.Zero) + { + return; + } + + SetStatus(reason + ",正在重新读取控件树……", null); + BeginTreeRead(_treeRootHandle, _treeUiaRoot, _treeWindow, reason); + } + + /// + /// Experimental: asks the target to switch its accessibility support on. It changes state + /// inside the target application, so it never runs unless the operator clicks it. + /// + private void ActivateTargetAccessibility() + { + NativeWindowInfo selected = GetSelectedWindow(); + IntPtr handle = _treeRootHandle != IntPtr.Zero + ? _treeRootHandle + : (selected == null ? IntPtr.Zero : selected.Handle); + if (handle == IntPtr.Zero) + { + SetStatus("请先选中窗口或拾取控件,再尝试激活目标无障碍。", null); + return; + } + + try + { + SetStatus(_activationService.Activate(handle), null); + } + catch (Exception ex) + { + AppLog.Error("激活目标无障碍失败。", ex); + SetStatus("激活目标无障碍失败。", ex); + return; + } + + // Give the target a moment to build its tree, then re-read honestly. + var timer = new System.Windows.Forms.Timer { Interval = ActivationRetryDelayMs + 500 }; + timer.Tick += delegate + { + timer.Stop(); + timer.Dispose(); + RereadCurrentTree("已尝试激活无障碍"); + }; + timer.Start(); + } + + private void ApplyTree(ControlTreeResult result, NativeWindowInfo inspectedWindow, string label) + { + _inspectedWindow = inspectedWindow; + _currentTreeRoot = result == null ? null : result.Root; + _currentTree = _currentTreeRoot; + LogTreeResult(result, label); + + RebuildTreeView(); + + if (_currentTreeRoot != null) + { + _resultTabs.SelectedTab = _controlTreeTab; + if (_controlTree.Nodes.Count > 0) + { + _controlTree.Nodes[0].Expand(); + } + } + + _exportButton.Enabled = _currentTreeRoot != null; + _exportListButton.Enabled = _lastListResult != null; + _activateButton.Enabled = _treeRootHandle != IntPtr.Zero; + _currentElement = _currentTreeRoot == null ? null : _currentTreeRoot.Uia; + _readListButton.Enabled = _currentElement != null && _currentElement.IsAvailable && + _currentElement.Element != null && !_picker.IsPicking; + _propertyGrid.SelectedObject = SelectedObjectFor(_currentTreeRoot); + _monitorEditor.SetCurrentNode(_currentTreeRoot, _inspectedWindow); + ShowNodeProperties(_currentTreeRoot); + + string source = result == null ? "(无)" : result.UsedSource.ToString(); + string note = result == null ? null : result.Note; + bool complete = _currentTreeRoot != null && _currentTreeRoot.ChildrenComplete; + string message = string.Format( + "控件树读取完成(来源 {0},节点 {1} 个){2}", + source, + result == null ? 0 : result.NodeCount, + complete ? "。" : ",但结果不完整:" + DescribeIncomplete(_currentTreeRoot)); + if (!string.IsNullOrEmpty(note)) + { + message += Environment.NewLine + note; + } + + int nodes = _currentTreeRoot == null ? 0 : ControlTreeService.CountNodes(_currentTreeRoot); + if (!complete && nodes <= 1) + { + message += Environment.NewLine + + "该来源只看到窗口本身。可切换「控件树来源」试试 MSAA / Win32,或点「尝试激活目标无障碍」。"; + } + else if (nodes > 1 && nodes <= 8 && ContainsTitleBar(_currentTreeRoot)) + { + message += Environment.NewLine + + "只读到窗口边框(标题栏按钮),没读到里面的控件。" + + "如果目标界面确实有内容:稍等再选一次(这类程序的内容树是异步生成的)," + + "或切换「控件树来源」为 MSAA / Win32,也可以点「尝试激活目标无障碍」。"; + } + + SetStatus(message, null); + } + + /// + /// The first concrete reason a tree is incomplete. The root only carries the placeholder + /// "DescendantIncomplete", which tells the operator nothing, so the tree is searched for the + /// node that actually hit a limit or a provider error. + /// + private static string DescribeIncomplete(ControlTreeNode node) + { + string concrete = FindConcreteIncomplete(node); + if (!string.IsNullOrEmpty(concrete)) + { + return ExplainIncomplete(concrete); + } + + return node == null || string.IsNullOrEmpty(node.ChildrenError) + ? "原因未知" + : ExplainIncomplete(node.ChildrenError); + } + + private static string FindConcreteIncomplete(ControlTreeNode node) + { + if (node == null) + { + return null; + } + + if (!node.ChildrenComplete && !string.IsNullOrEmpty(node.ChildrenError) && + !string.Equals(node.ChildrenError, "DescendantIncomplete", StringComparison.Ordinal)) + { + return node.ChildrenError; + } + + foreach (ControlTreeNode child in node.Children) + { + string found = FindConcreteIncomplete(child); + if (!string.IsNullOrEmpty(found)) + { + return found; + } + } + + return null; + } + + private static string ExplainIncomplete(string code) + { + switch (code) + { + case "MaxDepthReached": + return "达到最大深度(下面可能还有控件)"; + case "MaxNodesReached": + return "达到节点数上限"; + case "Canceled": + return "读取被取消"; + case "TimedOut": + return "读取超时"; + case "ReadFailed": + return "读取过程出错"; + case "UiAutomationUnavailable": + return "该窗口无法通过此来源读取"; + case "DescendantIncomplete": + return "某个子节点不完整"; + default: + return code; + } + } + + private static bool ContainsTitleBar(ControlTreeNode node) + { + if (node == null) + { + return false; + } + + if (node.Uia != null && string.Equals(node.Uia.ControlType, "ControlType.TitleBar", StringComparison.Ordinal)) + { + return true; + } + + foreach (ControlTreeNode child in node.Children) + { + if (ContainsTitleBar(child)) + { + return true; + } + } + + return false; + } + + /// + /// Shows a node in the property grid. RuntimeId is filled on demand here: the tree snapshot + /// leaves it empty because reading it costs a cross-process call per node, which would make + /// large trees slow — but an empty RuntimeId in the grid is confusing. + /// + private void ShowNodeProperties(ControlTreeNode node) + { + UiaElementInfo element = node == null ? null : node.Uia; + if (element != null) + { + element.EnsureRuntimeId(); + } + + _propertyGrid.SelectedObject = SelectedObjectFor(node); + _propertyGrid.Refresh(); + } + + /// Object shown in the property grid for a node, per source. + private static object SelectedObjectFor(ControlTreeNode node) + { + if (node == null) + { + return null; + } + + switch (node.Source) + { + case ControlTreeSource.Msaa: + return node.Msaa; + case ControlTreeSource.Win32: + return node.Window; + default: + return node.Uia; + } + } + + /// + /// A single-node tree is a meaningful result, not a failure: it means the target exposed no + /// controls to that source. Saying so in the log is the difference between "read failed" and + /// "this source cannot see inside". + /// + private static void LogTreeResult(ControlTreeResult result, string label) + { + if (result == null || result.Root == null) + { + AppLog.Warn("控件树结果:空(" + label + ")。"); + return; + } + + AppLog.Info("控件树结果:" + label + + ";来源=" + result.UsedSource + + ";节点数=" + result.NodeCount + + ";完整=" + result.Root.ChildrenComplete + + (result.Root.ChildrenComplete ? string.Empty : ";不完整原因=" + DescribeIncomplete(result.Root)) + + (string.IsNullOrEmpty(result.Note) ? string.Empty : ";说明=" + result.Note)); + if (result.NodeCount <= 1) + { + AppLog.Warn("该来源没有读到任何子节点(" + result.UsedSource + + ")。若目标界面确实有控件,可切换 MSAA / Win32 来源,或点「尝试激活目标无障碍」;" + + "浏览器内核/自绘界面可能三者都读不到,这是目标程序未暴露,而不是列表为空。"); + } + } + + /// + /// Rebuilds the visible tree from the model, applying the search criteria. Filtering hides + /// non-matching nodes but keeps their ancestors (a tree without its path is unreadable), and + /// matching nodes are highlighted and collected for ▲/▼ navigation. + /// + private void RebuildTreeView() + { + TreeSearchCriteria criteria = _treeSearchPanel.Criteria; + bool filter = _treeSearchPanel.OnlyMatches; + _treeMatches.Clear(); + _controlTree.BeginUpdate(); + try + { + _controlTree.Nodes.Clear(); + if (_currentTreeRoot != null) + { + TreeNode root = BuildTreeNode(_currentTreeRoot, string.Empty, criteria, filter); + if (root != null) + { + _controlTree.Nodes.Add(root); + root.Expand(); + } + } + } + finally + { + _controlTree.EndUpdate(); + } + + _treeSearchPanel.SetMatchCount(_treeMatches.Count); + _treeSearchPanel.SetNavigationEnabled(_treeMatches.Count > 0); + if (!criteria.IsEmpty) + { + AppLog.Info("控件树搜索:匹配 " + _treeMatches.Count + " 项" + (filter ? "(仅显示匹配)" : "(全部显示,匹配项高亮)")); + } + } + + private TreeNode BuildTreeNode(ControlTreeNode node, string parentPath, TreeSearchCriteria criteria, bool filter) + { + if (node == null) + { + return null; + } + + string text = node.Describe(); + string path = string.IsNullOrEmpty(parentPath) ? text : parentPath + " > " + text; + bool focused = node.Uia != null && node.Uia.HasKeyboardFocus.HasValue && node.Uia.HasKeyboardFocus.Value; + bool selfMatches = criteria.Matches(node, path, focused); + + var treeNode = new TreeNode(text) { Tag = node }; + int before = _treeMatches.Count; + foreach (ControlTreeNode child in node.Children) + { + TreeNode childNode = BuildTreeNode(child, path, criteria, filter); + if (childNode != null) + { + treeNode.Nodes.Add(childNode); + } + } + + bool descendantMatches = _treeMatches.Count > before; + if (selfMatches) + { + _treeMatches.Add(treeNode); + treeNode.BackColor = Color.LightYellow; + } + + if (!node.ChildrenComplete) + { + treeNode.Nodes.Add(new TreeNode("[读取不完整] " + (node.ChildrenError ?? "未知原因"))); + } + + if (node.Source == ControlTreeSource.Win32 && node.Window != null && !node.Window.IsVisible) + { + treeNode.ForeColor = Color.Gray; + } + + if (selfMatches || descendantMatches || criteria.IsEmpty || !filter) + { + return treeNode; + } + + return null; + } + + /// Moves the selection to the next/previous search hit, wrapping around. + private void NavigateTreeMatch(int direction) + { + if (_treeMatches.Count == 0) + { + return; + } + + int current = _controlTree.SelectedNode == null ? -1 : _treeMatches.IndexOf(_controlTree.SelectedNode); + int next; + if (current < 0) + { + next = direction > 0 ? 0 : _treeMatches.Count - 1; + } + else + { + next = (current + direction) % _treeMatches.Count; + if (next < 0) + { + next += _treeMatches.Count; + } + } + + TreeNode target = _treeMatches[next]; + target.EnsureVisible(); + _controlTree.SelectedNode = target; + } + + private TreeNode CreateTreeNode(ControlTreeNode node) + { + return BuildTreeNode(node, string.Empty, new TreeSearchCriteria(), false); + } + + private void ControlTreeOnAfterSelect(object sender, TreeViewEventArgs e) + { + CancelListRead(); + _lastListResult = null; + ClearListResultGrid(); + _exportListButton.Enabled = false; + + var node = e.Node == null ? null : e.Node.Tag as ControlTreeNode; + _currentElement = node == null ? null : node.Uia; + _propertyGrid.SelectedObject = SelectedObjectFor(node); + _monitorEditor.SetCurrentNode(node, _inspectedWindow); + ShowNodeProperties(node); + + if (_currentElement != null && _currentElement.IsAvailable && _currentElement.Element != null) + { + _readListButton.Enabled = !_picker.IsPicking; + return; + } + + _readListButton.Enabled = false; + if (node != null && node.Source != ControlTreeSource.Uia) + { + SetStatus("当前节点来自 " + node.Source + + " 来源,没有 UIA 元素,因此不能读取列表、也不能加入控件监控列表;" + + "可切换「控件树来源」为 UIA 后重试。", null); + } + } + + // ------------------------------------------------------------------ list read + + private void ReadSelectedList() + { + if (_currentElement == null || !_currentElement.IsAvailable || _currentElement.Element == null) + { + SetStatus("当前控件没有可用的 UIA 元素。", null); + return; + } + + if (Interlocked.Increment(ref _activeReads) > MaxConcurrentReads) + { + Interlocked.Decrement(ref _activeReads); + AppLog.Warn("已有 " + _activeReads + " 个读取任务未返回,拒绝新的列表读取。"); + SetStatus("上一个读取仍未返回,目标可能已无响应;请稍后再试。", null); + return; + } + + CancelListRead(); + _listReadCancellation = CancellationTokenSource.CreateLinkedTokenSource(_shutdown.Token); + CancellationToken token = _listReadCancellation.Token; + int sequence = ++_listReadSequence; + AutomationElement element = _currentElement.Element; + _lastListReadElement = _currentElement.ControlType + " / " + _currentElement.Name + + " / RuntimeId=" + _currentElement.RuntimeId; + _readListButton.Enabled = false; + SetStatus("正在读取标准 UIA 列表模式……", null); + AppLog.Info("开始读取列表:" + _lastListReadElement); + + var options = new ListReadOptions(); + Stopwatch stopwatch = Stopwatch.StartNew(); + Task task = Task.Factory.StartNew( + delegate + { + try + { + ListReadResult readResult = _listReaderService.Read(element, options, token); + if (NeedsStructureDiagnostics(readResult)) + { + LogStructureDiagnostics(element, readResult); + } + + return readResult; + } + catch (Exception ex) + { + AppLog.Error("列表读取异常。", ex); + LogStructureDiagnostics(element, null); + return new ListReadResult + { + Status = ListReadStatus.Failed, + IsComplete = false, + Error = ex.GetType().Name + ": " + ex.Message + }; + } + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + + task.ContinueWith( + delegate(Task completed) + { + Interlocked.Decrement(ref _activeReads); + stopwatch.Stop(); + if (IsDisposed || !IsHandleCreated || sequence != _listReadSequence) + { + return; + } + + try + { + BeginInvoke((Action)delegate + { + if (IsDisposed || sequence != _listReadSequence) + { + return; + } + + _readListButton.Enabled = true; + if (completed.IsCanceled) + { + SetStatus("列表读取已取消。", null); + } + else if (completed.IsFaulted) + { + SetStatus("列表读取失败。", completed.Exception.GetBaseException()); + } + else + { + _lastListResult = completed.Result; + _exportListButton.Enabled = _lastListResult != null; + AppLog.Info("列表读取耗时 " + stopwatch.ElapsedMilliseconds + " ms。"); + ApplyListResult(completed.Result); + if (_lastListResult != null && + (_lastListResult.Status == ListReadStatus.Unsupported || + _lastListResult.Status == ListReadStatus.Failed)) + { + _resultTabs.SelectedTab = _listResultTab; + } + } + }); + } + catch (InvalidOperationException) + { + // The form handle can be destroyed between the state check and BeginInvoke during shutdown. + } + catch (Exception ex) when (ex is ObjectDisposedException) + { + // The form is already closing; no UI update is needed. + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + } + + /// Summary for a selected window: the window itself has no UIA path. + /// + /// Dumps what the picked element and its neighbours actually expose. This is the only way to + /// tell "the list is empty" apart from "this provider exposes nothing readable". + /// + /// + /// Diagnostics are wanted for failures, but also for every traversal-derived result: a + /// "1 row x 1 column" downgrade looks like success in the status line while telling us nothing + /// about the target. + /// + private static bool NeedsStructureDiagnostics(ListReadResult result) + { + if (result == null) + { + return true; + } + + if (result.Status == ListReadStatus.Unsupported || result.Status == ListReadStatus.Failed) + { + return true; + } + + return result.Source == ListReadSource.UiaElementTraversal + || (result.RowsRead <= 1 && result.ColumnCount <= 1); + } + + private void LogStructureDiagnostics(AutomationElement element, ListReadResult listResult) + { + try + { + AppLog.Warn("列表读取结果需要排查(状态=" + (listResult == null ? "(无)" : listResult.Status.ToString()) + + ";来源=" + (listResult == null ? "(无)" : listResult.Source.ToString()) + + ";行=" + (listResult == null ? 0 : listResult.RowsRead) + + ";列=" + (listResult == null ? 0 : listResult.ColumnCount) + ")。"); + AppLog.Warn("以下是被拾取元素及其上级的结构(用于判断 Provider 是否暴露控件):"); + foreach (string line in _uiAutomationService.DescribeChain(element, DiagnosticsAncestorDepth, DiagnosticsChildCount)) + { + AppLog.Warn(line); + } + + AppLog.Warn("被拾取元素的直接子元素:"); + foreach (string line in _uiAutomationService.DescribeChildren(element, DiagnosticsChildCount)) + { + AppLog.Warn(line); + } + } + catch (Exception ex) + { + AppLog.Error("输出结构诊断时失败。", ex); + } + } + + private void CancelInspection() + { + if (_inspectionCancellation != null) + { + _inspectionCancellation.Cancel(); + _inspectionCancellation.Dispose(); + _inspectionCancellation = null; + } + } + + private void CancelListRead() + { + _listReadSequence++; + if (_listReadCancellation != null) + { + _listReadCancellation.Cancel(); + _listReadCancellation.Dispose(); + _listReadCancellation = null; + } + } + + private void ClearListResultGrid() + { + if (_listResultTable != null) + { + _listResultTable.Clear(); + _listResultTable.Columns.Clear(); + } + + if (_listResultGrid != null) + { + _listResultGrid.DataSource = null; + } + } + + private DataTable BuildListGridTable(ListReadResult result) + { + var table = new DataTable(); + int columnCount = result.ColumnNames.Count; + foreach (ListRowResult row in result.Rows) + { + foreach (ListCellResult cell in row.Cells) + { + if (cell.ColumnIndex >= 0) + { + columnCount = Math.Max(columnCount, cell.ColumnIndex + 1); + } + } + } + + columnCount = Math.Min(columnCount, 10000); + for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) + { + string name = columnIndex < result.ColumnNames.Count + ? result.ColumnNames[columnIndex] + : null; + string baseName = string.IsNullOrEmpty(name) ? "Column" + columnIndex : name; + string uniqueName = baseName; + int suffix = 2; + while (table.Columns.Contains(uniqueName)) + { + uniqueName = baseName + "_" + suffix++; + } + + table.Columns.Add(uniqueName); + } + + foreach (ListRowResult row in result.Rows) + { + DataRow dataRow = table.NewRow(); + foreach (ListCellResult cell in row.Cells) + { + if (cell.ColumnIndex < 0 || cell.ColumnIndex >= table.Columns.Count) + { + continue; + } + + dataRow[cell.ColumnIndex] = cell.ValueAvailable + ? (object)(cell.Value ?? string.Empty) + : "[不可用] " + (cell.Error ?? "未暴露值"); + } + table.Rows.Add(dataRow); + } + + return table; + } + + private void ApplyListResult(ListReadResult result) + { + if (result == null) + { + SetStatus("列表读取没有返回结果。", null); + return; + } + + string rowsText = result.TotalRowsKnown + ? result.RowCount.ToString() + : "未知(已读 " + result.RowsRead + " 行)"; + string message = string.Format( + "列表读取状态:{0};来源:{1};总行数:{2};总列数:{3};已读行数:{4};已读单元格:{5};完整:{6}", + result.Status, + result.Source, + rowsText, + result.ColumnCount, + result.RowsRead, + result.CellsRead, + result.IsComplete ? "是" : "否"); + if (!string.IsNullOrEmpty(result.Error)) + { + message += ";" + result.Error; + } + if (result.Errors.Count > 0) + { + message += ";错误数:" + result.Errors.Count; + } + + _listResultGrid.DataSource = null; + _listResultTable.Clear(); + _listResultTable.Columns.Clear(); + DataTable table = BuildListGridTable(result); + foreach (DataColumn column in table.Columns) + { + _listResultTable.Columns.Add(column.ColumnName); + } + foreach (DataRow row in table.Rows) + { + _listResultTable.ImportRow(row); + } + _listResultGrid.DataSource = _listResultTable; + if (result.SelectedItems.Count > 0) + { + message += ";选中项:" + result.SelectedItems.Count; + } + + SetStatus(message, null); + _listResultHint.Text = BuildListResultHint(result); + + // Notices are downgrade remarks, not failures: show them without inflating the error count. + if (result.Notices.Count > 0) + { + SetStatus(message + Environment.NewLine + "提示:" + string.Join(";", result.Notices.ToArray()), null); + } + } + + /// + /// Explains the "列表结果" tab. An empty table is the normal outcome for controls that expose + /// no table structure, and saying why is the difference between "useless" and "diagnosable". + /// + private static string BuildListResultHint(ListReadResult result) + { + if (result == null) + { + return "还没有读取。选中控件后点「读取选中控件列表」。"; + } + + if (result.RowsRead > 0) + { + return string.Format( + "已读取 {0} 行 × {1} 列(来源 {2},状态 {3})。{4}", + result.RowsRead, result.ColumnCount, result.Source, result.Status, + result.IsComplete ? string.Empty : "结果不完整:" + (result.Error ?? "见下方提示。")); + } + + var builder = new System.Text.StringBuilder(); + builder.Append("没有读到行。状态=").Append(result.Status).Append(";来源=").Append(result.Source); + builder.Append(";已向上查找 ").Append("若干").Append(" 级并尝试了子元素遍历。"); + if (!string.IsNullOrEmpty(result.Error)) + { + builder.Append(" 原因:").Append(result.Error); + } + + builder.Append(" 可依次尝试:① 切换「控件树来源」为 MSAA / Win32 再读;② 点「尝试激活目标无障碍」后重读;"); + builder.Append("③ 若目标是不暴露表格结构的自绘界面(如 OCS),任何 UI Automation 工具都读不到逐单元格数据。"); + return builder.ToString(); + } + + private void ExportLastListResult() + { + if (_lastListResult == null) + { + SetStatus("当前没有可导出的列表读取结果。", null); + return; + } + + DialogResult consent = MessageBox.Show( + this, + "列表结果可能包含患者或检查敏感信息。确认仅将数据保存到你选择的本地文件吗?", + "敏感数据提示", + MessageBoxButtons.YesNo, + MessageBoxIcon.Warning); + if (consent != DialogResult.Yes) + { + return; + } + + using (var dialog = new SaveFileDialog + { + Filter = "JSON 文件|*.json|CSV 文件|*.csv", + FilterIndex = 1, + FileName = "list-result-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".json" + }) + { + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + + try + { + bool exportCsv = dialog.FilterIndex == 2; + string extension = exportCsv ? ".csv" : ".json"; + string exportPath = Path.ChangeExtension(dialog.FileName, extension); + if (exportCsv) + { + _listResultExporter.ExportCsv(_lastListResult, exportPath); + } + else + { + _listResultExporter.ExportJson(_lastListResult, exportPath); + } + + AppLog.Info("列表读取结果已导出:" + exportPath); + SetStatus("列表读取结果已导出:" + exportPath, null); + } + catch (Exception ex) + { + AppLog.Error("列表结果导出失败。", ex); + SetStatus("列表结果导出失败。", ex); + } + } + } + + private void ExportCurrentTree() + { + if (_currentTreeRoot == null) + { + return; + } + + using (var dialog = new SaveFileDialog + { + Filter = "JSON 文件|*.json|所有文件|*.*", + FileName = "uia-tree-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".json" + }) + { + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + + try + { + _treeExporter.Export(_currentTreeRoot, _currentTreeSource, dialog.FileName); + AppLog.Info("控件树已导出:" + dialog.FileName); + SetStatus("控件树已导出:" + dialog.FileName, null); + } + catch (Exception ex) + { + AppLog.Error("控件树导出失败。", ex); + SetStatus("控件树导出失败。", ex); + } + } + } + + private NativeWindowInfo GetSelectedWindow() + { + return _windowList.SelectedItems.Count == 0 + ? null + : _windowList.SelectedItems[0].Tag as NativeWindowInfo; + } + + /// Shows where a monitor entry actually is, by drawing the same non-activating frame the picker uses. + private void MonitorEditorOnControlLocated(object sender, ControlLocatedEventArgs e) + { + _propertyGrid.SelectedObject = e.Definition; + _propertyGrid.Refresh(); + if (e.Bounds == null || !e.Bounds.IsValid) + { + SetStatus("已定位到控件,但该控件没有可用的屏幕矩形,无法高亮。", null); + return; + } + + _locateHighlight.ShowHighlight(e.Bounds.ToRectangle()); + SetStatus("已在屏幕上高亮该控件(" + e.Bounds + ")。", null); + } + + /// The property grid doubles as the editor for the selected monitor entry. + private void MonitorEditorOnDefinitionSelected(object sender, DefinitionSelectedEventArgs e) + { + if (e.Definition == null) + { + return; + } + + _propertyGrid.SelectedObject = e.Definition; + _propertyGrid.Refresh(); + } + + private void MonitorEditorOnStatusChanged(object sender, ControlMonitorStatusEventArgs e) + { + SetStatus(e.Message, e.Exception); + } + + private void SetStatus(string message, Exception exception) + { + string detail = exception == null ? string.Empty : Environment.NewLine + exception.GetType().Name + ": " + exception.Message; + _statusText.Text = DateTime.Now.ToString("HH:mm:ss") + " " + message + detail; + if (exception != null) + { + AppLog.Error(message, exception); + } + } + + private void MainFormOnFormClosing(object sender, FormClosingEventArgs e) + { + if (_monitorEditor.HasUnsavedChanges) + { + DialogResult answer = MessageBox.Show( + this, + "控件监控列表有尚未保存的修改,确定退出吗?", + "控件监控列表", + MessageBoxButtons.YesNo, + MessageBoxIcon.Warning); + if (answer != DialogResult.Yes) + { + e.Cancel = true; + return; + } + } + + try + { + if (_floatingToolbar != null) + { + _floatingToolbar.SavePosition(); + _settingsStore.Save(_settings); + _floatingToolbar.Hide(); + } + + _commandRunner.RunExitCommands(_settings); + _commandRunner.Dispose(); + } + catch (Exception ex) + { + AppLog.Error("退出钩子执行失败。", ex); + } + + _autoInspectTimer.Stop(); + _treeReadTimer.Stop(); + _treeReadTimer.Tick -= TreeReadTimerOnTick; + _treeReadTimer.Dispose(); + _inspectionSequence++; + _listReadSequence++; + CancelInspection(); + CancelListRead(); + _shutdown.Cancel(); + _picker.Dispose(); + _activationService.Dispose(); + _locateHighlight.Dispose(); + _autoInspectTimer.Tick -= AutoInspectTimerOnTick; + _autoInspectTimer.Dispose(); + _shutdown.Dispose(); + } + } +} diff --git a/src/pacs_win_uia/UI/PickerOverlayForm.cs b/src/pacs_win_uia/UI/PickerOverlayForm.cs new file mode 100644 index 0000000..52316f1 --- /dev/null +++ b/src/pacs_win_uia/UI/PickerOverlayForm.cs @@ -0,0 +1,238 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using pacs_win_uia.Interop; + +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; } + } + + /// + /// Virtual-screen picker overlay. It captures the confirmation click without + /// activating, and briefly hides itself only while resolving the underlying HWND. + /// + public sealed class PickerOverlayForm : Form + { + private readonly Timer _timer; + private bool _leftButtonWasDown; + private bool _inputArmed; + private Point _lastCursorPosition; + private bool _hasCursorPosition; + private bool _overlayNativeVisible; + + public event EventHandler CursorMoved; + public event EventHandler EscapePressed; + public event EventHandler LeftButtonReleased; + + public PickerOverlayForm() + { + FormBorderStyle = FormBorderStyle.None; + ShowInTaskbar = false; + StartPosition = FormStartPosition.Manual; + TopMost = true; + BackColor = Color.Magenta; + TransparencyKey = Color.Magenta; + Cursor = Cursors.Cross; + DoubleBuffered = true; + Bounds = SystemInformation.VirtualScreen; + _timer = new Timer { Interval = 40 }; + _timer.Tick += TimerOnTick; + } + + public Point CurrentScreenPoint + { + get { return _lastCursorPosition; } + } + + public IntPtr CurrentWindowHandle { get; private set; } + + public IntPtr RefreshCurrentWindowHandle(Point screenPoint) + { + _lastCursorPosition = screenPoint; + _hasCursorPosition = true; + CurrentWindowHandle = ResolveUnderlyingWindow(screenPoint); + return CurrentWindowHandle; + } + + protected override bool ShowWithoutActivation + { + get { return true; } + } + + protected override CreateParams CreateParams + { + get + { + CreateParams parameters = base.CreateParams; + parameters.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW | + NativeMethods.WS_EX_NOACTIVATE; + return parameters; + } + } + + protected override void WndProc(ref Message message) + { + if (message.Msg == NativeMethods.WM_NCHITTEST) + { + // Capture the confirmation click so it cannot reach the PACS window. + message.Result = new IntPtr(NativeMethods.HTCLIENT); + return; + } + + if (message.Msg == NativeMethods.WM_MOUSEACTIVATE) + { + message.Result = new IntPtr(NativeMethods.MA_NOACTIVATE); + return; + } + + base.WndProc(ref message); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button == MouseButtons.Left && _inputArmed) + { + _leftButtonWasDown = true; + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (e.Button == MouseButtons.Left && _inputArmed && _leftButtonWasDown) + { + _leftButtonWasDown = false; + EventHandler releaseHandler = LeftButtonReleased; + if (releaseHandler != null) + { + releaseHandler(this, EventArgs.Empty); + } + } + } + + private void TimerOnTick(object sender, EventArgs e) + { + if ((NativeMethods.GetAsyncKeyState(NativeMethods.VK_ESCAPE) & 0x8000) != 0) + { + EventHandler escapeHandler = EscapePressed; + if (escapeHandler != null) + { + escapeHandler(this, EventArgs.Empty); + } + return; + } + + NativeMethods.POINT nativePoint; + if (NativeMethods.GetCursorPos(out nativePoint)) + { + Point point = nativePoint.ToDrawingPoint(); + if (!_hasCursorPosition || _lastCursorPosition != point) + { + _lastCursorPosition = point; + _hasCursorPosition = true; + CurrentWindowHandle = ResolveUnderlyingWindow(point); + EventHandler cursorHandler = CursorMoved; + if (cursorHandler != null) + { + cursorHandler(this, new CursorPositionEventArgs(point, CurrentWindowHandle)); + } + } + } + + bool leftButtonDown = (NativeMethods.GetAsyncKeyState(NativeMethods.VK_LBUTTON) & 0x8000) != 0; + if (!_inputArmed) + { + // Do not treat the mouse-up which released the toolbar button as a pick. + if (!leftButtonDown) + { + _inputArmed = true; + _leftButtonWasDown = false; + } + return; + } + + if (_leftButtonWasDown && !leftButtonDown) + { + EventHandler releaseHandler = LeftButtonReleased; + if (releaseHandler != null) + { + releaseHandler(this, EventArgs.Empty); + } + } + + _leftButtonWasDown = leftButtonDown; + } + + private IntPtr ResolveUnderlyingWindow(Point screenPoint) + { + bool wasVisible = _overlayNativeVisible; + if (wasVisible) + { + NativeMethods.ShowWindow(Handle, NativeMethods.SW_HIDE); + _overlayNativeVisible = false; + } + + try + { + return NativeMethods.WindowFromPoint(screenPoint); + } + finally + { + if (wasVisible && !IsDisposed && IsHandleCreated) + { + NativeMethods.ShowWindow(Handle, NativeMethods.SW_SHOWNOACTIVATE); + _overlayNativeVisible = true; + } + } + } + + protected override void OnShown(EventArgs e) + { + base.OnShown(e); + _overlayNativeVisible = true; + NativeMethods.ShowWindow(Handle, NativeMethods.SW_SHOWNOACTIVATE); + NativeMethods.POINT nativePoint; + if (NativeMethods.GetCursorPos(out nativePoint)) + { + _lastCursorPosition = nativePoint.ToDrawingPoint(); + _hasCursorPosition = true; + CurrentWindowHandle = ResolveUnderlyingWindow(_lastCursorPosition); + EventHandler cursorHandler = CursorMoved; + if (cursorHandler != null) + { + cursorHandler(this, new CursorPositionEventArgs(_lastCursorPosition, CurrentWindowHandle)); + } + } + + _leftButtonWasDown = (NativeMethods.GetAsyncKeyState(NativeMethods.VK_LBUTTON) & 0x8000) != 0; + _inputArmed = !_leftButtonWasDown; + _timer.Start(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _timer.Stop(); + _overlayNativeVisible = false; + _timer.Dispose(); + CursorMoved = null; + EscapePressed = null; + LeftButtonReleased = null; + } + + base.Dispose(disposing); + } + } +} diff --git a/src/pacs_win_uia/UI/ScrollHostPanel.cs b/src/pacs_win_uia/UI/ScrollHostPanel.cs new file mode 100644 index 0000000..795936f --- /dev/null +++ b/src/pacs_win_uia/UI/ScrollHostPanel.cs @@ -0,0 +1,87 @@ +using System; +using System.Windows.Forms; + +namespace pacs_win_uia.UI +{ + /// + /// Hosts a single control in a scrolling viewport. A control that supports AutoScroll only + /// scrolls when its child is larger than the viewport, so the content is kept at + /// : on a narrow screen a bottom scrollbar appears and the + /// right-hand part of the content stays reachable instead of being clipped. + /// + public sealed class ScrollHostPanel : Panel + { + private Control _content; + private bool _layingOut; + + public ScrollHostPanel() + { + AutoScroll = true; + MinimumContentWidth = 460; + } + + public int MinimumContentWidth { get; set; } + + public Control Content + { + get { return _content; } + set + { + if (ReferenceEquals(_content, value)) + { + return; + } + + if (_content != null) + { + Controls.Remove(_content); + } + + _content = value; + if (_content != null) + { + _content.Dock = DockStyle.None; + Controls.Add(_content); + } + + LayoutContent(); + } + } + + protected override void OnLayout(LayoutEventArgs levent) + { + base.OnLayout(levent); + LayoutContent(); + } + + protected override void OnClientSizeChanged(EventArgs e) + { + base.OnClientSizeChanged(e); + LayoutContent(); + } + + private void LayoutContent() + { + if (_content == null || _layingOut) + { + return; + } + + _layingOut = true; + try + { + // ClientSize already excludes any scrollbar that is currently shown. + int width = Math.Max(ClientSize.Width, MinimumContentWidth); + int height = Math.Max(ClientSize.Height, 0); + if (_content.Width != width || _content.Height != height || _content.Left != 0 || _content.Top != 0) + { + _content.SetBounds(0, 0, width, height); + } + } + finally + { + _layingOut = false; + } + } + } +} diff --git a/src/pacs_win_uia/UI/SettingsForm.cs b/src/pacs_win_uia/UI/SettingsForm.cs new file mode 100644 index 0000000..29fa74d --- /dev/null +++ b/src/pacs_win_uia/UI/SettingsForm.cs @@ -0,0 +1,543 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Reflection; +using System.Windows.Forms; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Models; +using pacs_win_uia.Services; + +namespace pacs_win_uia.UI +{ + /// + /// Settings dialog. Every page edits a copy of the settings; nothing is written until 保存, so a + /// cancelled dialog cannot half-apply a change. + /// + public sealed class SettingsForm : Form + { + private readonly AppSettings _settings; + private readonly AppSettingsStore _store; + private readonly CommandRunner _runner; + private readonly BindingList _continuous; + private readonly BindingList _once; + private readonly TextBox _outputBox; + + private CheckBox _autoReadTree; + private CheckBox _highlightForeground; + private CheckBox _floatingEnabled; + private NumericUpDown _floatingOpacity; + private CheckedListBox _floatingActions; + private NumericUpDown _treeDepth; + private NumericUpDown _treeNodes; + private NumericUpDown _treeTimeout; + private NumericUpDown _readTimeout; + private CheckBox _skipDisabled; + private TextBox _onStart; + private TextBox _onExit; + private CheckBox _ocrEnabled; + private TextBox _ocrEngine; + private TextBox _ocrLanguage; + private TextBox _ocrDirectory; + + public SettingsForm(AppSettings settings, AppSettingsStore store, CommandRunner runner) + { + _settings = settings ?? AppSettings.CreateDefault(); + _store = store ?? new AppSettingsStore(); + _runner = runner; + _settings.Normalize(); + + _continuous = new BindingList(CopyCommands(_settings.Commands.Continuous)); + _once = new BindingList(CopyCommands(_settings.Commands.Once)); + + Text = "设置 - PACS Windows UI Automation Inspector"; + StartPosition = FormStartPosition.CenterParent; + MinimumSize = new Size(720, 560); + Size = new Size(860, 640); + ShowInTaskbar = false; + + var tabs = new TabControl { Dock = DockStyle.Fill }; + tabs.TabPages.Add(BuildAboutPage()); + tabs.TabPages.Add(BuildUiPage()); + tabs.TabPages.Add(BuildFloatingPage()); + tabs.TabPages.Add(BuildCommandPage()); + tabs.TabPages.Add(BuildOcrPage()); + + var buttons = new FlowLayoutPanel + { + Dock = DockStyle.Bottom, + Height = 44, + FlowDirection = FlowDirection.RightToLeft, + Padding = new Padding(6) + }; + var cancel = new Button { Text = "取消", AutoSize = true, DialogResult = DialogResult.Cancel }; + var save = new Button { Text = "保存", AutoSize = true }; + save.Click += delegate { Save(); }; + buttons.Controls.Add(cancel); + buttons.Controls.Add(save); + var openFolder = new Button { Text = "打开配置文件所在目录", AutoSize = true }; + openFolder.Click += delegate { OpenFolder(_store.PreferredPath); }; + buttons.Controls.Add(openFolder); + + _outputBox = new TextBox + { + Multiline = true, + ReadOnly = true, + ScrollBars = ScrollBars.Vertical, + Dock = DockStyle.Bottom, + Height = 28, + Visible = false + }; + + Controls.Add(tabs); + Controls.Add(_outputBox); + Controls.Add(buttons); + + if (_runner != null) + { + _runner.Output += delegate(object sender, CommandOutputEventArgs e) { AppendOutput(e); }; + } + } + + /// The edited settings; only meaningful when the dialog returned OK. + public AppSettings Result + { + get { return _settings; } + } + + private static IList CopyCommands(IList source) + { + var copy = new List(); + if (source != null) + { + foreach (CommandDefinition command in source) + { + if (command == null) + { + continue; + } + + copy.Add(new CommandDefinition + { + Name = command.Name, + CommandLine = command.CommandLine, + WorkingDirectory = command.WorkingDirectory, + IntervalSeconds = command.IntervalSeconds, + TimeoutSeconds = command.TimeoutSeconds, + Enabled = command.Enabled + }); + } + } + + return copy; + } + + // ------------------------------------------------------------------ pages + + private TabPage BuildAboutPage() + { + var page = new TabPage("关于"); + var text = new TextBox + { + Dock = DockStyle.Fill, + Multiline = true, + ReadOnly = true, + ScrollBars = ScrollBars.Vertical, + WordWrap = true, + BackColor = SystemColors.Window + }; + Version version = Assembly.GetExecutingAssembly().GetName().Version; + text.Text = string.Join(Environment.NewLine, new[] + { + "PACS Windows UI Automation Inspector", + "版本:" + version, + "", + "能力边界(如实说明,不夸大):", + "· 控件树/拾取支持三种来源:UIA、MSAA、Win32。三者是独立视图,不保证互相对应。", + "· 可靠保证:选定窗口的每个后代窗口都会出现在 Win32 树里(HWND/类名/矩形)。", + "· 尽力而为:窗口标题、以及任何控件内容——取决于目标程序是否暴露 UIA/MSAA。", + "· 做不到:以 asInvoker 运行,读不到以管理员提权的进程;GPU/自绘且无提供者的界面三种来源都看不到。", + "· 列表读取只使用 UIA 的 Grid/Table 模式与子元素遍历;MSAA 对列表的保真度更低。", + "· OCR 本轮未实现,设置里只有占位字段。", + "", + "配置文件位置:", + "· 设置:" + _store.PreferredPath, + "· 设置(备用,exe 目录不可写时):" + _store.FallbackPath, + "· 监控定义:" + Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "pacs_win_uia", "control-monitors.json"), + "", + "安全:默认只读;不注入目标进程、不修改内存、不绕过授权;命令以当前用户身份执行。", + "不要把患者信息放到命令行或上传到外部服务。" + }); + page.Controls.Add(text); + return page; + } + + private TabPage BuildUiPage() + { + var page = new TabPage("界面"); + var panel = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + FlowDirection = FlowDirection.TopDown, + WrapContents = false, + Padding = new Padding(10) + }; + + _autoReadTree = new CheckBox + { + Text = "在窗口列表里选中一行时自动读取控件树", + Checked = _settings.Ui.AutoReadTreeOnSelect, + AutoSize = true + }; + _highlightForeground = new CheckBox + { + Text = "窗口列表里用底色标出当前前台窗口", + Checked = _settings.Ui.HighlightForegroundWindow, + AutoSize = true + }; + _treeDepth = AddNumber(panel, "控件树最大深度(1-32):", _settings.Ui.TreeMaxDepth, 1, 32); + _treeNodes = AddNumber(panel, "控件树最大节点数(50-50000):", _settings.Ui.TreeMaxNodes, 50, 50000); + _treeTimeout = AddNumber(panel, "控件树读取超时(秒):", _settings.Ui.TreeTimeoutSeconds, 1, 600); + _readTimeout = AddNumber(panel, "无界面读取默认等待超时(秒,0=不等待):", _settings.Read.DefaultTimeoutSeconds, 0, 3600); + _skipDisabled = new CheckBox + { + Text = "无界面读取时跳过已停用的监控条目", + Checked = _settings.Read.SkipDisabled, + AutoSize = true + }; + + panel.Controls.Add(_autoReadTree); + panel.Controls.Add(_highlightForeground); + panel.Controls.Add(_skipDisabled); + page.Controls.Add(panel); + return page; + } + + 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) }); + var box = new NumericUpDown + { + Minimum = minimum, + Maximum = maximum, + Value = Math.Max(minimum, Math.Min(maximum, value)), + Width = 100 + }; + parent.Controls.Add(box); + return box; + } + + private TabPage BuildFloatingPage() + { + var page = new TabPage("悬浮按钮"); + var panel = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + FlowDirection = FlowDirection.TopDown, + WrapContents = false, + Padding = new Padding(10) + }; + _floatingEnabled = new CheckBox + { + Text = "显示悬浮按钮条(置顶、不抢焦点、可拖动)", + Checked = _settings.FloatingButton.Enabled, + AutoSize = true + }; + panel.Controls.Add(_floatingEnabled); + panel.Controls.Add(new Label { Text = "不透明度(20-100):", AutoSize = true, Padding = new Padding(0, 8, 0, 0) }); + _floatingOpacity = new NumericUpDown + { + Minimum = 20, + Maximum = 100, + Value = Math.Max(20, Math.Min(100, _settings.FloatingButton.OpacityPercent)), + Width = 100 + }; + panel.Controls.Add(_floatingOpacity); + panel.Controls.Add(new Label { Text = "显示的按钮:", AutoSize = true, Padding = new Padding(0, 8, 0, 0) }); + _floatingActions = new CheckedListBox { Width = 320, Height = 150, CheckOnClick = true }; + IList configured = _settings.FloatingButton.Actions ?? new List(); + foreach (string action in FloatingToolbarForm.KnownActions) + { + bool isChecked = configured.Count == 0 || configured.Contains(action); + _floatingActions.Items.Add(action, isChecked); + } + + panel.Controls.Add(_floatingActions); + panel.Controls.Add(new Label + { + Text = "「定位到控件」= 在监控列表里定位并高亮目标;「读取全部监控项」= 逐个定位并读取当前值。", + AutoSize = true, + ForeColor = Color.DarkSlateGray, + Padding = new Padding(0, 6, 0, 0) + }); + page.Controls.Add(panel); + return page; + } + + private TabPage BuildCommandPage() + { + var page = new TabPage("命令"); + var layout = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 1, RowCount = 6 }; + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, 30)); + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, 30)); + layout.RowStyles.Add(new RowStyle(SizeType.Percent, 40)); + layout.RowStyles.Add(new RowStyle(SizeType.Percent, 40)); + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, 34)); + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, 60)); + + _onStart = AddCommandLine(layout, "启动执行(工具启动时执行一次):", _settings.Commands.OnStart); + _onExit = AddCommandLine(layout, "结束执行(工具退出时执行一次):", _settings.Commands.OnExit); + + layout.Controls.Add(new Label + { + Text = "on(持续执行,按间隔循环,可随时停止)", + AutoSize = true, + Font = new Font(SystemFonts.DefaultFont, FontStyle.Bold) + }); + layout.Controls.Add(BuildCommandGrid(_continuous)); + + layout.Controls.Add(new Label + { + Text = "once(只在启动时执行一次)", + AutoSize = true, + Font = new Font(SystemFonts.DefaultFont, FontStyle.Bold) + }); + layout.Controls.Add(BuildCommandGrid(_once)); + + var buttons = new FlowLayoutPanel { Dock = DockStyle.Fill, WrapContents = false }; + var runSelected = new Button { Text = "立即执行选中的 once 命令", AutoSize = true }; + runSelected.Click += delegate { RunSelectedOnce(); }; + buttons.Controls.Add(runSelected); + var stopContinuous = new Button { Text = "停止持续命令", AutoSize = true }; + stopContinuous.Click += delegate + { + if (_runner != null) + { + _runner.StopContinuous(); + ShowOutput("已停止持续命令。"); + } + }; + buttons.Controls.Add(stopContinuous); + var startContinuous = new Button { Text = "启动持续命令", AutoSize = true }; + startContinuous.Click += delegate + { + if (_runner != null) + { + _runner.StartContinuous(_continuous); + ShowOutput("已按当前列表启动持续命令(保存后下次启动同样生效)。"); + } + }; + buttons.Controls.Add(startContinuous); + layout.Controls.Add(buttons); + + layout.Controls.Add(new Label + { + Text = "命令通过 cmd.exe /c 执行,以当前用户身份运行;输出会记入控制台日志。" + + "不要把患者信息写进命令行。", + AutoSize = true, + ForeColor = Color.DarkSlateGray + }); + page.Controls.Add(layout); + return page; + } + + private TextBox AddCommandLine(TableLayoutPanel layout, string label, string value) + { + var panel = new Panel { Dock = DockStyle.Fill }; + panel.Controls.Add(new TextBox { Dock = DockStyle.Fill, Text = value ?? string.Empty }); + var caption = new Label { Dock = DockStyle.Left, Text = label, AutoSize = false, Width = 260, TextAlign = ContentAlignment.MiddleLeft }; + panel.Controls.Add(caption); + layout.Controls.Add(panel); + // The caller keeps the text box through the panel's first control. + return (TextBox)panel.Controls[0]; + } + + private DataGridView BuildCommandGrid(BindingList list) + { + var grid = new DataGridView + { + Dock = DockStyle.Fill, + AutoGenerateColumns = false, + AllowUserToAddRows = true, + AllowUserToDeleteRows = true, + AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill + }; + grid.Columns.Add(new DataGridViewCheckBoxColumn { HeaderText = "启用", DataPropertyName = "Enabled", FillWeight = 8 }); + grid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "名称", DataPropertyName = "Name", FillWeight = 20 }); + grid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "命令行", DataPropertyName = "CommandLine", FillWeight = 40 }); + grid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "工作目录", DataPropertyName = "WorkingDirectory", FillWeight = 20 }); + grid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "间隔秒", DataPropertyName = "IntervalSeconds", FillWeight = 8 }); + grid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "超时秒", DataPropertyName = "TimeoutSeconds", FillWeight = 8 }); + grid.DataSource = list; + return grid; + } + + private TabPage BuildOcrPage() + { + var page = new TabPage("OCR"); + var panel = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + FlowDirection = FlowDirection.TopDown, + WrapContents = false, + Padding = new Padding(10) + }; + panel.Controls.Add(new Label + { + Text = "本轮未实现:下面只是配置占位,不会执行任何识别。", + AutoSize = true, + Font = new Font(SystemFonts.DefaultFont, FontStyle.Bold), + ForeColor = Color.Firebrick + }); + _ocrEnabled = new CheckBox { Text = "启用 OCR(未实现)", Checked = _settings.Ocr.Enabled, AutoSize = true, Enabled = false }; + panel.Controls.Add(_ocrEnabled); + panel.Controls.Add(new Label { Text = "识别引擎(预留):", AutoSize = true, Padding = new Padding(0, 8, 0, 0) }); + _ocrEngine = new TextBox { Width = 260, Text = _settings.Ocr.Engine ?? string.Empty, Enabled = false }; + panel.Controls.Add(_ocrEngine); + panel.Controls.Add(new Label { Text = "语言(预留):", AutoSize = true, Padding = new Padding(0, 8, 0, 0) }); + _ocrLanguage = new TextBox { Width = 160, Text = _settings.Ocr.Language ?? string.Empty, Enabled = false }; + panel.Controls.Add(_ocrLanguage); + panel.Controls.Add(new Label { Text = "截图目录(预留):", AutoSize = true, Padding = new Padding(0, 8, 0, 0) }); + _ocrDirectory = new TextBox { Width = 360, Text = _settings.Ocr.CaptureDirectory ?? string.Empty, Enabled = false }; + panel.Controls.Add(_ocrDirectory); + panel.Controls.Add(new Label + { + Text = "实现时需引入识别引擎与中文语言包,并明确“截图可能包含患者信息”,默认不上传外部服务。", + AutoSize = true, + ForeColor = Color.DarkSlateGray, + Padding = new Padding(0, 8, 0, 0) + }); + page.Controls.Add(panel); + return page; + } + + // ------------------------------------------------------------------ actions + + private void Save() + { + _settings.Ui.AutoReadTreeOnSelect = _autoReadTree.Checked; + _settings.Ui.HighlightForegroundWindow = _highlightForeground.Checked; + _settings.Ui.TreeMaxDepth = (int)_treeDepth.Value; + _settings.Ui.TreeMaxNodes = (int)_treeNodes.Value; + _settings.Ui.TreeTimeoutSeconds = (int)_treeTimeout.Value; + _settings.Read.DefaultTimeoutSeconds = (int)_readTimeout.Value; + _settings.Read.SkipDisabled = _skipDisabled.Checked; + + _settings.FloatingButton.Enabled = _floatingEnabled.Checked; + _settings.FloatingButton.OpacityPercent = (int)_floatingOpacity.Value; + var actions = new List(); + foreach (object item in _floatingActions.CheckedItems) + { + actions.Add(Convert.ToString(item)); + } + + _settings.FloatingButton.Actions = actions; + + _settings.Commands.OnStart = _onStart.Text; + _settings.Commands.OnExit = _onExit.Text; + _settings.Commands.Continuous = new List(_continuous); + _settings.Commands.Once = new List(_once); + + if (!_store.Save(_settings)) + { + MessageBox.Show( + this, + "设置保存失败:exe 目录与用户目录都不可写。", + "设置", + MessageBoxButtons.OK, + MessageBoxIcon.Warning); + return; + } + + AppLog.Info("设置已保存:" + _store.FilePath); + DialogResult = DialogResult.OK; + Close(); + } + + private void RunSelectedOnce() + { + if (_runner == null) + { + ShowOutput("命令执行器不可用。"); + return; + } + + CommandDefinition command = null; + if (_once.Count > 0) + { + command = _once[0]; + } + + if (command == null) + { + ShowOutput("once 列表为空,先新增一条命令。"); + return; + } + + ShowOutput("正在执行:" + command.CommandLine); + CommandResult result = _runner.RunCommand(command, "手动"); + ShowOutput(result.TimedOut + ? "执行超时。" + : result.Error != null + ? "执行失败:" + result.Error + : "执行结束,退出码 " + result.ExitCode + "。"); + } + + private void AppendOutput(CommandOutputEventArgs e) + { + if (IsDisposed) + { + return; + } + + if (InvokeRequired) + { + try + { + BeginInvoke((Action)delegate { AppendOutput(e); }); + } + catch (Exception) + { + // The dialog is closing. + } + + return; + } + + ShowOutput((e.IsError ? "[stderr] " : "[out] ") + e.Text); + } + + private void ShowOutput(string line) + { + _outputBox.Visible = true; + _outputBox.Text = DateTime.Now.ToString("HH:mm:ss") + " " + line + Environment.NewLine + _outputBox.Text; + if (_outputBox.Text.Length > 20000) + { + _outputBox.Text = _outputBox.Text.Substring(0, 20000); + } + } + + private static void OpenFolder(string filePath) + { + try + { + string directory = Path.GetDirectoryName(filePath); + if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory)) + { + Process.Start("explorer.exe", "\"" + directory + "\""); + return; + } + + MessageBox.Show("目录不存在:" + directory, "设置"); + } + catch (Exception ex) + { + MessageBox.Show("打开目录失败:" + ex.Message, "设置"); + } + } + } +} diff --git a/src/pacs_win_uia/app.config b/src/pacs_win_uia/app.config new file mode 100644 index 0000000..3a36f12 --- /dev/null +++ b/src/pacs_win_uia/app.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/pacs_win_uia/app.manifest b/src/pacs_win_uia/app.manifest new file mode 100644 index 0000000..dc52860 --- /dev/null +++ b/src/pacs_win_uia/app.manifest @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + true + true + + + diff --git a/src/pacs_win_uia/pacs_win_uia.csproj b/src/pacs_win_uia/pacs_win_uia.csproj new file mode 100644 index 0000000..ed6c117 --- /dev/null +++ b/src/pacs_win_uia/pacs_win_uia.csproj @@ -0,0 +1,117 @@ + + + + + + Debug + AnyCPU + {C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202} + Exe + Properties + pacs_win_uia + pacs_win_uia + v4.8 + 512 + true + false + app.manifest + + + + AnyCPU + true + full + false + ..\..\bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + + AnyCPU + pdbonly + true + ..\..\bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + + PreserveNewest + + + + + diff --git a/src/pacs_win_uia/settings.json b/src/pacs_win_uia/settings.json new file mode 100644 index 0000000..6104c27 --- /dev/null +++ b/src/pacs_win_uia/settings.json @@ -0,0 +1,33 @@ +{ + "Version": 1, + "Ui": { + "AutoReadTreeOnSelect": true, + "HighlightForegroundWindow": true, + "TreeMaxDepth": 12, + "TreeMaxNodes": 3000, + "TreeTimeoutSeconds": 10 + }, + "FloatingButton": { + "Enabled": false, + "OpacityPercent": 90, + "X": 60, + "Y": 60, + "Actions": [ "读取选中控件列表", "定位到控件", "读取全部监控项" ] + }, + "Commands": { + "OnStart": "", + "OnExit": "", + "Continuous": [], + "Once": [] + }, + "Ocr": { + "Enabled": false, + "Engine": "(未实现)", + "Language": "zh-CN", + "CaptureDirectory": "" + }, + "Read": { + "DefaultTimeoutSeconds": 10, + "SkipDisabled": true + } +}