From 170790ff1248173140328157c110683a09bf7951 Mon Sep 17 00:00:00 2001 From: zimoyin <2556608754@qq.com> Date: Tue, 13 Oct 2026 19:28:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E3=80=8C=E9=80=89=E4=B8=AD?= =?UTF-8?q?=E8=A1=8C=E6=96=87=E6=9C=AC=E3=80=8D=E5=8F=96=E5=80=BC=E9=94=AE?= =?UTF-8?q?=EF=BC=9B=E7=82=B9=E5=87=BB=E6=8E=A7=E4=BB=B6=E6=A1=86=E5=BF=85?= =?UTF-8?q?=E5=AE=9A=E5=90=8C=E6=AD=A5=E6=8E=A7=E4=BB=B6=E5=B1=9E=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ControlValueKeys 新增「选中行文本」:在列表容器上直接读当前选中行的文字 (SelectionPattern 第一个选中项 → Value → Text → Name);没有选中行时明确报错 - 控件框点选回调:无论该节点是否在当前控件树里,都更新控件属性(SelectedObject + ShowNodeProperties + 下方 Path 横条),并在状态栏说明是否同时选中了树节点 实测(夹具列表,启动时选中第 2 行):列表行数=3、列数=2、选中项数=1、选中行文本=项目 2 回归 29/29 通过 --- docs/XPath定位.md | 1 + docs/代码导览.md | 12 +- src/pacs_win_uia/Models/ControlLocator.cs | 8 +- .../Services/ControlValueReader.cs | 92 ++ src/pacs_win_uia/UI/MainForm.cs | 19 +- src/pacs_win_uia/UI/NodeMapOverlayForm.cs | 809 +++++++++++++++++- tests/regression/ValueKeyTests.cs | 4 +- 7 files changed, 909 insertions(+), 36 deletions(-) diff --git a/docs/XPath定位.md b/docs/XPath定位.md index 6ce7a63..55ae8de 100644 --- a/docs/XPath定位.md +++ b/docs/XPath定位.md @@ -225,6 +225,7 @@ XPath 中的 `Edit`、`Button` 等来自 UIA 控件类型。不同来源也会 | `列表行数` | 行数(GridPattern 优先,其次 TablePattern) | | `列表列数` | 列数 | | `列表选中项数` | 当前选中项数 | +| `选中行文本` | 当前选中那一行的文字(在列表容器上直接读,不用先选行) | 需要完整行列数据时仍然用「读取选中控件列表」。 diff --git a/docs/代码导览.md b/docs/代码导览.md index 4459e5e..8f2dbe0 100644 --- a/docs/代码导览.md +++ b/docs/代码导览.md @@ -65,7 +65,7 @@ MainForm(UI/MainForm.cs) 三栏主界面:窗口列表 | 控件树/列 | 悬浮条外观(自绘/透明) | `UI/FloatingToolbarForm.cs` | layered window,注意 GDI 释放 | | 遮挡/可见性判断 | `Services/WindowVisibility.cs` | 两个 API 用途不同,见文件头 | | 高亮框/跟随 | `Services/HighlightFollower.cs` | 跟随锚点窗口的相对偏移 | -| 全部控件框绘制 | `UI/NodeMapOverlayForm.cs` | 只在前台窗口且未遮挡处绘制 | +| 全部控件框绘制 / 侧边按钮与过滤 | `UI/NodeMapOverlayForm.cs` | 只在前台窗口且未遮挡处绘制;点框即选中控件树节点并刷新控件属性 | | 拾取器 | `Picker/CrosshairPicker.cs` + `UI/PickerOverlayForm.cs` | 不抢焦点、吞左键 | | 单实例/转发 | `Services/SingleInstanceService.cs` + `Program.cs` | Mutex + 命名管道 | | 无界面读取 | `Services/HeadlessConfigReader.cs` | 每条独立计时,统计口径在文件头 | @@ -105,6 +105,16 @@ MainForm(UI/MainForm.cs) 三栏主界面:窗口列表 | 控件树/列 --- +## 四·三、空树自动开无障碍(浏览器/CEF/UWP) + +读到**空树 / 只有窗口边框 / 里面有渲染窗口却没有子树**时,`ControlTreeService` 会自动请求目标开启无障碍(`AccessibilityActivationService`)并等 900ms 重读一次: + +- 目标确实开了:节点数变多,采用新结果,状态栏说明"重读后节点 N → M"; +- 目标没暴露:如实说明"该目标没有向系统暴露无障碍树",不会假装读到了; +- 同一窗口 60 秒内只自动激活一次; +- 主程序里**只嵌了一块浏览器区域**(部分 DOM)同样适用:激活只影响那块渲染窗口,重读后它和原生控件一起出现在同一棵树里,**不会改写根窗口**; +- 不想要工具动目标:设置 →「界面」里关掉"读到空树时自动请求目标开启无障碍"。 + ## 四·五、配置文件位置(都在 exe 同目录) | 文件 | 用途 | diff --git a/src/pacs_win_uia/Models/ControlLocator.cs b/src/pacs_win_uia/Models/ControlLocator.cs index 0bfe1ec..1c40912 100644 --- a/src/pacs_win_uia/Models/ControlLocator.cs +++ b/src/pacs_win_uia/Models/ControlLocator.cs @@ -177,6 +177,12 @@ namespace pacs_win_uia.Models public const string ListSelectedCount = "列表选中项数"; + /// + /// 跨来源键(UIA):列表容器上直接读「当前选中那一行的文字」。 + /// 用它在监控里盯住"现在选中的是哪一行",不必写 XPath 选行再取值。 + /// + public const string SelectedRowText = "选中行文本"; + /// 跨来源键:这个控件是不是被选中的那一个。 public const string Selected = "选中状态"; @@ -198,7 +204,7 @@ namespace pacs_win_uia.Models TextContent, "Name", "AutomationId", "ControlType", "ClassName", "FrameworkId", "RuntimeId", "IsEnabled", "IsOffscreen", "BoundingRectangle", "Value", "Text", Selected, "IsSelected", Focused, "HasKeyboardFocus", - ListRowCount, ListColumnCount, ListSelectedCount + ListRowCount, ListColumnCount, ListSelectedCount, SelectedRowText }; // Msaa:MSAA 来源可读取的属性键列表。 diff --git a/src/pacs_win_uia/Services/ControlValueReader.cs b/src/pacs_win_uia/Services/ControlValueReader.cs index efd3304..3d8b3fe 100644 --- a/src/pacs_win_uia/Services/ControlValueReader.cs +++ b/src/pacs_win_uia/Services/ControlValueReader.cs @@ -232,6 +232,8 @@ namespace pacs_win_uia.Services return TryReadUiaListDimension(info, false, out value, out error); case ControlValueKeys.ListSelectedCount: return TryReadUiaSelectionCount(info, out value, out error); + case ControlValueKeys.SelectedRowText: + return TryReadUiaSelectedRowText(info, options, out value, out error); // 选中状态:支持“选中状态”(Selected) 与 “IsSelected” 两个别名。 case ControlValueKeys.Selected: case "IsSelected": @@ -287,6 +289,96 @@ namespace pacs_win_uia.Services } + + /// + /// 列表容器上的「选中行文本」:取 SelectionPattern 的第一个选中项,再按 + /// Value → Text → Name 读它的内容(与「文本内容」同一套顺序)。 + /// 没有选中项时明确报"当前没有选中行",而不是给一个空字符串。 + /// + // 选中行文本:容器 → 第一个选中项 → 该行内容。 + private static bool TryReadUiaSelectedRowText(UiaElementInfo info, ListReadOptions options, + out string value, out string error) + { + value = null; + error = null; + AutomationElement element = info == null ? null : info.Element; + if (element == null) + { + error = "UIA 元素引用不可用(可能是回读时未重新绑定)。"; + return false; + } + + try + { + object pattern; + if (!element.TryGetCurrentPattern(SelectionPattern.Pattern, out pattern)) + { + error = "该控件不支持 SelectionPattern,读不到选中行(列表行本身可以用 XPath 的 @IsSelected 选)。"; + return false; + } + + AutomationElement[] items = ((SelectionPattern)pattern).Current.GetSelection(); + if (items == null || items.Length == 0) + { + error = "该列表当前没有选中行。"; + return false; + } + + AutomationElement row = items[0]; + // 先试模式值(输入/富文本类的行),再退回名称(普通列表行)。 + foreach (string key in new[] { "Value", "Text" }) + { + try + { + object rowPattern; + if (string.Equals(key, "Value", StringComparison.Ordinal) && + row.TryGetCurrentPattern(ValuePattern.Pattern, out rowPattern)) + { + string candidate = ((ValuePattern)rowPattern).Current.Value; + if (!string.IsNullOrEmpty(candidate)) + { + value = candidate; + return true; + } + + continue; + } + + if (string.Equals(key, "Text", StringComparison.Ordinal) && + row.TryGetCurrentPattern(TextPattern.Pattern, out rowPattern)) + { + int maxLength = options == null ? 32768 : options.MaxTextLength; + string candidate = ((TextPattern)rowPattern).DocumentRange.GetText(Math.Max(1, maxLength)); + if (!string.IsNullOrEmpty(candidate)) + { + value = candidate.TrimEnd('\r', '\n'); + return true; + } + } + } + catch (Exception) + { + // 该行不支持这个模式:继续试下一个来源。 + } + } + + string name = row.Current.Name; + if (!string.IsNullOrEmpty(name)) + { + value = name; + return true; + } + + error = "选中行没有可读的文本(Value/Text/Name 都为空)。"; + return false; + } + catch (Exception ex) + { + error = "读取选中行文本失败:" + ex.GetType().Name + ": " + ex.Message; + return false; + } + } + /// /// 列表行数 / 列数:优先 GridPattern,其次 TablePattern(两者都有的控件以 Grid 为准)。 /// 只有容器(List/DataGrid/Table/Tree)才支持,普通控件会明确报"不是列表"。 diff --git a/src/pacs_win_uia/UI/MainForm.cs b/src/pacs_win_uia/UI/MainForm.cs index 83ec1d4..3f0544a 100644 --- a/src/pacs_win_uia/UI/MainForm.cs +++ b/src/pacs_win_uia/UI/MainForm.cs @@ -535,17 +535,30 @@ namespace pacs_win_uia _locateFollower.Hidden += LocateFollowerOnHidden; _nodeMapOverlay = new NodeMapOverlayForm { RefreshIntervalMs = _settings.Ui.TreeRefreshIntervalMs }; _nodeMapOverlay.MapExited += delegate { _nodeMapItem.Checked = false; }; + // 点击控件框:在控件树里展开并选中该节点,同时更新控件属性;顺带把 path 复制到剪贴板。 + // 节点不在当前树里(例如框属于另一个窗口的树)时,也要更新控件属性,不能什么都不发生。 _nodeMapOverlay.NodeSelected += delegate(object sender, NodeMapSelectionEventArgs e) { var node = e.Node as ControlTreeNode; if (node == null) return; - SelectTreeNodeFor(node); + + bool selectedInTree = SelectTreeNodeFor(node); + _propertyGrid.SelectedObject = SelectedObjectFor(node); + _monitorEditor.SetCurrentNode(node, _inspectedWindow); + ShowNodeProperties(node); + UpdateSelectedPathText(node); + try { if (!string.IsNullOrEmpty(e.Path)) Clipboard.SetText(e.Path); - SetStatus("已复制该框的 path:" + e.Path + "(滚轮可切换重叠节点)", null); + SetStatus("已选中该框的控件:" + node.Describe() + + (selectedInTree ? "(控件树已展开并选中)" : "(该节点不在当前控件树里,只更新了控件属性)") + + ";path 已复制:" + e.Path + "(滚轮可切换重叠节点)", null); + } + catch (Exception ex) + { + SetStatus("复制 path 失败。", ex); } - catch (Exception ex) { SetStatus("复制 path 失败。", ex); } }; _statusText = new TextBox { diff --git a/src/pacs_win_uia/UI/NodeMapOverlayForm.cs b/src/pacs_win_uia/UI/NodeMapOverlayForm.cs index db1ca92..9fb1fe2 100644 --- a/src/pacs_win_uia/UI/NodeMapOverlayForm.cs +++ b/src/pacs_win_uia/UI/NodeMapOverlayForm.cs @@ -23,8 +23,28 @@ // 框坐标以锚定顶层窗口左上角为原点存成相对偏移(Entry.Offset);RefreshMap 时若目标不可见/ // 被完全遮挡/非前台,就隐藏表面(HideSurfaces)并退出选取模式,目标恢复后自动复现。 // -// “要改什么就改哪里”:快照/几何 → ReplaceItems / RefreshMap;选取与钩子 → SetSelectionMode / -// MouseHookCallback / KeyboardHookCallback;绘制 → OnPaint。 +// 侧栏(NodeMapActionsForm)新增的联动功能: +// · 父节点 / 上一个 / 下一个:用 MapItems 自身的 Node 引用推父子关系(items 覆盖整棵树, +// 每个 Node 的 Children 也在 items 里),不依赖 MainForm;点击后发 NodeSelected,并把整条 +// 祖先链加粗高亮(其余框变淡)。 +// · 点框联动:点/滚轮选中一个框后同样发 NodeSelected(带 Node/Index/Path/ScreenPoint), +// MainForm 负责在控件树里选中并刷新属性(现有行为,本次只是把“当前项”也记进覆盖层)。 +// · 显示框的信息:类型 / 名称 / 宽×高 / (X,Y) / 层级路径,显示鼠标下优先、否则当前选中的框。 +// · 过滤与搜索:搜索词 + 控件类型下拉(类型从 items 收集)+“仅选中及其祖先/后代”勾选。 +// · 悬停标签:只在鼠标下的那个框旁画一个“类型:名称 宽×高”小标签(120-300ms 定时器读 +// Cursor.Position 在内存里命中测试,不装鼠标钩子)。 +// · 其它:一键复制当前框 path、显示/隐藏标签开关。 +// +// 硬性约束(勿破坏):不抢焦点/不激活/不吞普通模式点击——覆盖层保留 +// WS_EX_NOACTIVATE|WS_EX_TRANSPARENT + HTTRANSPARENT;侧栏只是 NOACTIVATE(可点按钮,不点击穿透)。 +// 目标最小化/关闭/被别的程序完全遮挡时的隐藏逻辑保持不变;本工具自身窗口不算遮挡。 +// 每帧只读 GetWindowRect(RefreshMap),过滤/命中测试全在内存里,不新增跨进程 UIA 调用。 +// 搜索框/类型下拉在 NOACTIVATE 侧栏上通过 AttachThreadInput 抢到键盘焦点(见 NodeMapInputFocus), +// 这样能输入但不会激活侧栏、也不会抢走目标窗口的激活态。 +// +// “要改什么就改哪里”:快照/几何/父子关系 → ReplaceItems / RefreshMap;选取与钩子 → SetSelectionMode / +// MouseHookCallback / KeyboardHookCallback;绘制(框、祖先链、悬停标签)→ OnPaint;过滤 → ApplyFilter / +// MatchesFilter;导航 → GoParent / GoSibling;侧栏控件与布局 → NodeMapActionsForm。 // ============================================================================ using System; using System.Collections.Generic; @@ -32,12 +52,101 @@ using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Runtime.InteropServices; +using System.Text; using System.Windows.Forms; using pacs_win_uia.Interop; +using pacs_win_uia.Models; using pacs_win_uia.Services; namespace pacs_win_uia.UI { + // ------------------------------------------------------------------------- + // NodeMapNodeInfo —— 从覆盖层持有的 Node(object,实际是 ControlTreeNode)里只读地取显示信息。 + // 只读内存快照字段(Uia/Msaa/Window),绝不触发任何跨进程调用,可安全用于每帧的过滤/标签。 + // ------------------------------------------------------------------------- + internal static class NodeMapNodeInfo + { + /// 把 Node 安全转成 ControlTreeNode(不是则返回 null)。 + internal static ControlTreeNode AsNode(object node) { return node as ControlTreeNode; } + + /// 显示名称:UIA.Name → MSAA.Name → 窗口标题。 + internal static string GetName(object node) + { + ControlTreeNode n = node as ControlTreeNode; + if (n == null) return null; + if (n.Uia != null && !string.IsNullOrEmpty(n.Uia.Name)) return n.Uia.Name; + if (n.Msaa != null && !string.IsNullOrEmpty(n.Msaa.Name)) return n.Msaa.Name; + if (n.Window != null && !string.IsNullOrEmpty(n.Window.Title)) return n.Window.Title; + return null; + } + + /// 类型文本:UIA.ControlType → MSAA.RoleText → 按来源给个通用名。 + internal static string GetType(object node) + { + ControlTreeNode n = node as ControlTreeNode; + if (n == null) return null; + if (n.Uia != null && !string.IsNullOrEmpty(n.Uia.ControlType)) return n.Uia.ControlType; + if (n.Msaa != null && !string.IsNullOrEmpty(n.Msaa.RoleText)) return n.Msaa.RoleText; + switch (n.Source) + { + case ControlTreeSource.Win32: return "Win32窗口"; + case ControlTreeSource.Msaa: return "MSAA节点"; + default: return "UIA控件"; + } + } + + /// 类名:UIA.ClassName → 窗口类名。 + internal static string GetClassName(object node) + { + ControlTreeNode n = node as ControlTreeNode; + if (n == null) return null; + if (n.Uia != null && !string.IsNullOrEmpty(n.Uia.ClassName)) return n.Uia.ClassName; + if (n.Window != null) return n.Window.ClassName; + return null; + } + + /// AutomationId(只有 UIA 节点有)。 + internal static string GetAutomationId(object node) + { + ControlTreeNode n = node as ControlTreeNode; + return n == null || n.Uia == null ? null : n.Uia.AutomationId; + } + } + + // ------------------------------------------------------------------------- + // NodeMapInputFocus —— 让 NOACTIVATE 侧栏上的输入控件(搜索框/下拉)能收到键盘输入, + // 但不激活侧栏、不抢目标窗口的激活态。做法:临时把本线程附到前台线程的输入队列, + // SetFocus 后再分离(经典技巧)。失败时静默放弃(按钮/鼠标选择仍可用)。 + // ------------------------------------------------------------------------- + internal static class NodeMapInputFocus + { + [DllImport("user32.dll", SetLastError = false)] + private static extern IntPtr SetFocus(IntPtr hWnd); + [DllImport("user32.dll", SetLastError = false)] + private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach); + [DllImport("kernel32.dll", SetLastError = false)] + private static extern uint GetCurrentThreadId(); + + /// 把键盘焦点强制给到指定控件(不激活其顶层窗口)。 + internal static void ForceFocus(Control control) + { + if (control == null || control.IsDisposed || !control.IsHandleCreated) return; + IntPtr foreground = NativeMethods.GetForegroundWindow(); + uint processId; + uint foregroundThread = foreground == IntPtr.Zero ? 0 : + NativeMethods.GetWindowThreadProcessId(foreground, out processId); + uint currentThread = GetCurrentThreadId(); + bool attached = false; + if (foregroundThread != 0 && foregroundThread != currentThread) + attached = AttachThreadInput(foregroundThread, currentThread, true); + try { SetFocus(control.Handle); } + finally + { + if (attached) AttachThreadInput(foregroundThread, currentThread, false); + } + } + } + /// An immutable tree-refresh snapshot; Bounds are screen coordinates, Node is caller-owned. /// 一次树刷新后的不可变快照:屏幕矩形 + 调用方拥有的节点对象;供覆盖层只读使用。 public class NodeMapItem @@ -106,6 +215,17 @@ namespace pacs_win_uia.UI internal NodeMapItem Item; /// 相对锚定窗口左上角的偏移矩形(跟随窗口移动)。 internal Rectangle Offset; + // ---- 以下为过滤/标签/信息面板用的预计算文本(只在 ReplaceItems 时算一次,内存内使用)---- + /// 显示名称(来自 Node)。 + internal string Name; + /// 类型(来自 Node)。 + internal string Type; + /// 类名(来自 Node)。 + internal string ClassName; + /// AutomationId(来自 Node)。 + internal string AutomationId; + /// 是否通过当前过滤(false 则不画、不参与命中测试)。 + internal bool Visible = true; } /// UI 线程 300ms 刷新定时器。 @@ -137,6 +257,36 @@ namespace pacs_win_uia.UI /// 是否已有 _candidatePoint(用于“同点同候选”判断)。 private bool _hasCandidatePoint; + // ---- 选中/导航/父子关系(全部由 items 自身推导,不依赖 MainForm)---- + /// Node 引用 → Entry(引用相等;用于按节点找回条目、推父子关系)。 + private readonly Dictionary _entryByNode = new Dictionary(); + /// 子 Node 引用 → 父 Entry(由每个 Node 的 Children 反查得到)。 + private readonly Dictionary _parentOf = new Dictionary(); + /// 当前通过过滤、可见且有序的条目(导航在其上移动)。 + private readonly List _visibleEntries = new List(); + /// 当前选中项及其整条祖先链的 Node 引用集合(绘制加粗高亮用)。 + private readonly HashSet _chainNodes = new HashSet(); + /// 当前选中的节点(跨快照保活,按引用/Path 重新定位)。 + private object _currentNode; + /// 当前选中节点的 Path(Node 为 null 时的回退定位)。 + private string _currentPath; + /// 当前选中的条目(可能在过滤后被隐藏)。 + private Entry _currentEntry; + /// 祖先链里是否有可见项(否则整条链不可见时不进入“变淡”模式)。 + private bool _chainActive; + /// 鼠标下的条目(用于悬停标签与信息面板)。 + private Entry _hoverEntry; + /// 是否显示悬停标签。 + private bool _showLabels = true; + + // ---- 过滤状态(由侧栏控件驱动,见 OnFilterChanged)---- + /// 搜索词(匹配 Name/AutomationId/Class/Path/类型)。 + private string _filterText; + /// 类型过滤(空 = 全部类型)。 + private string _filterType; + /// 是否只保留“当前选中及其祖先/后代”。 + private bool _filterSelectedOnly; + /// 初始化窗体样式、创建刷新定时器与动作面板,并接线面板的选取/退出事件。 public NodeMapOverlayForm() { @@ -160,6 +310,28 @@ namespace pacs_win_uia.UI EventHandler handler = MapExited; if (handler != null) handler(this, EventArgs.Empty); }; + // --- 新增功能的事件接线(全部在 UI 线程,面板控件不点击穿透)--- + _actions.ParentRequested += delegate { GoParent(); }; + _actions.PrevRequested += delegate { GoSibling(-1); }; + _actions.NextRequested += delegate { GoSibling(1); }; + _actions.CopyPathRequested += delegate { CopyCurrentPath(); }; + _actions.FilterChanged += delegate { OnFilterChanged(); }; + _actions.LabelsChanged += delegate + { + _showLabels = _actions.LabelsChecked; + Invalidate(); + }; + _showLabels = _actions.LabelsChecked; + } + + /// 读取侧栏的过滤控件状态并刷新过滤(搜索词 / 类型 / 仅选中链路)。 + private void OnFilterChanged() + { + _filterText = _actions.SearchText; + _filterType = _actions.SelectedType; + _filterSelectedOnly = _actions.SelectedOnly; + ApplyFilter(); + UpdatePanelInfo(_hoverEntry != null ? _hoverEntry : _currentEntry); } /// 节点被选中时触发。 @@ -194,6 +366,36 @@ namespace pacs_win_uia.UI } } + /// 是否显示鼠标下的框旁边的文字标签(默认开)。 + public bool ShowLabels + { + get { return _showLabels; } + set + { + if (_showLabels == value) return; + _showLabels = value; + _actions.SetLabels(value); + Invalidate(); + } + } + + /// + /// 可选接口:把某个节点标成“当前”(加粗高亮其祖先链)。MainForm 若想在控件树里选节点时 + /// 也高亮覆盖层,可在树选中回调里调用;不调用也不影响本覆盖层自身的父子/上一个/下一个。 + /// + public void SetActiveNode(object node, string path = null) + { + _currentNode = node; + _currentPath = path; + Entry found; + _currentEntry = node != null && _entryByNode.TryGetValue(node, out found) ? found : null; + if (_currentEntry == null && !string.IsNullOrEmpty(path)) + _currentEntry = FindEntryByPath(path); + ApplyFilter(); + UpdatePanelInfo(_currentEntry); + Invalidate(); + } + /// 显示时不激活窗口。 protected override bool ShowWithoutActivation { get { return true; } } /// 扩展样式:工具窗口、不激活、鼠标穿透。 @@ -290,6 +492,9 @@ namespace pacs_win_uia.UI _version++; _pressedEntry = null; _entries.Clear(); + _entryByNode.Clear(); + _parentOf.Clear(); + _hoverEntry = null; if (items != null) { for (int index = 0; index < items.Count; index++) @@ -298,10 +503,86 @@ namespace pacs_win_uia.UI if (item == null || item.Bounds.Width <= 1 || item.Bounds.Height <= 1) continue; Rectangle offset = item.Bounds; offset.Offset(-bounds.Left, -bounds.Top); - _entries.Add(new Entry { Index = index, Item = item, Offset = offset }); + var entry = new Entry + { + Index = index, + Item = item, + Offset = offset, + Name = NodeMapNodeInfo.GetName(item.Node), + Type = NodeMapNodeInfo.GetType(item.Node), + ClassName = NodeMapNodeInfo.GetClassName(item.Node), + AutomationId = NodeMapNodeInfo.GetAutomationId(item.Node) + }; + _entries.Add(entry); + if (item.Node != null) _entryByNode[item.Node] = entry; } } + BuildParentMap(); + ResolveCurrentEntry(); + UpdateTypeFilter(); ClearCandidates(); + ApplyFilter(); + } + + /// + /// 从 items 自身推父子关系:对每个节点,遍历它的 Children(也是 items 里的节点), + /// 记下“子 → 父”。引用相等即可(ControlTreeNode 未重写 Equals)。不依赖 MainForm。 + /// + private void BuildParentMap() + { + foreach (Entry entry in _entries) + { + ControlTreeNode node = NodeMapNodeInfo.AsNode(entry.Item.Node); + if (node == null) continue; + foreach (ControlTreeNode child in node.Children) + { + Entry childEntry; + if (child != null && _entryByNode.TryGetValue(child, out childEntry)) + _parentOf[child] = entry; + } + } + } + + /// 按当前选中节点(引用优先、Path 回退)在新快照里重新定位 _currentEntry。 + private void ResolveCurrentEntry() + { + Entry found; + _currentEntry = _currentNode != null && _entryByNode.TryGetValue(_currentNode, out found) ? found : null; + if (_currentEntry == null && !string.IsNullOrEmpty(_currentPath)) _currentEntry = FindEntryByPath(_currentPath); + RebuildChain(); + } + + /// 按 Path 在快照里找条目(Node 为 null 时的回退)。 + private Entry FindEntryByPath(string path) + { + foreach (Entry entry in _entries) + if (string.Equals(entry.Item.Path, path, StringComparison.Ordinal)) return entry; + return null; + } + + /// 重建“当前选中及其祖先”的 Node 引用集合(供加粗高亮)。 + private void RebuildChain() + { + _chainNodes.Clear(); + Entry current = _currentEntry; + int guard = 0; + while (current != null && guard++ < 100000) + { + _chainNodes.Add(current.Item.Node != null ? (object)current.Item.Node : current); + Entry parent; + if (current.Item.Node == null || !_parentOf.TryGetValue(current.Item.Node, out parent)) break; + current = parent; + } + } + + /// 把 items 里出现的类型收集去重后推给侧栏下拉(保留用户已选类型)。 + private void UpdateTypeFilter() + { + var types = new List(); + foreach (Entry entry in _entries) + if (!string.IsNullOrEmpty(entry.Type) && !types.Contains(entry.Type)) types.Add(entry.Type); + types.Sort(StringComparer.Ordinal); + _actions.SetTypes(types, _filterType); } /// 结束地图会话:清空快照、退出选取模式、隐藏所有表面并停表。 @@ -311,6 +592,15 @@ namespace pacs_win_uia.UI _version++; _anchor = IntPtr.Zero; _entries.Clear(); + _entryByNode.Clear(); + _parentOf.Clear(); + _visibleEntries.Clear(); + _chainNodes.Clear(); + _chainActive = false; + _currentNode = null; + _currentPath = null; + _currentEntry = null; + _hoverEntry = null; SetSelectionMode(false); HideSurfaces(); _timer.Stop(); @@ -389,11 +679,12 @@ namespace pacs_win_uia.UI } if (!Visible) Show(); if (!_actions.Visible) _actions.Show(); - if (_selectionMode) - { - NativeMethods.POINT point; - if (NativeMethods.GetCursorPos(out point)) UpdateCandidates(point.ToDrawingPoint(), false); - } + // 每帧只读一次 Cursor.Position(本地),既驱动选取候选,也驱动悬停标签/信息面板。 + NativeMethods.POINT point; + bool hasCursor = NativeMethods.GetCursorPos(out point); + Point cursor = hasCursor ? point.ToDrawingPoint() : Point.Empty; + if (_selectionMode && hasCursor) UpdateCandidates(cursor, false); + if (hasCursor) UpdateHover(cursor); Invalidate(); } } @@ -445,7 +736,7 @@ namespace pacs_win_uia.UI Point local = new Point(point.X - bounds.Left, point.Y - bounds.Top); var hits = new List(); foreach (Entry entry in _entries) - if (entry.Offset.Contains(local)) hits.Add(entry); + if (entry.Visible && entry.Offset.Contains(local)) hits.Add(entry); hits.Sort(delegate(Entry left, Entry right) { int size = ((long)left.Offset.Width * left.Offset.Height).CompareTo((long)right.Offset.Width * right.Offset.Height); @@ -473,6 +764,236 @@ namespace pacs_win_uia.UI get { return _candidates.Count == 0 ? null : _candidates[_candidateIndex]; } } + // ------------------------------------------------------------------ 过滤 / 搜索 + + /// 按当前搜索词/类型/“仅选中”重算每条目的可见性,并刷新可见列表与祖先链。 + private void ApplyFilter() + { + _visibleEntries.Clear(); + foreach (Entry entry in _entries) + { + entry.Visible = MatchesFilter(entry); + if (entry.Visible) _visibleEntries.Add(entry); + } + if (_hoverEntry != null && !_hoverEntry.Visible) _hoverEntry = null; + RebuildChain(); + // 祖先链里只要有可见项就进入“其余框变淡”模式,避免整条链被过滤后还变淡。 + _chainActive = false; + if (_chainNodes.Count > 0) + foreach (Entry entry in _visibleEntries) + if (IsInChain(entry)) { _chainActive = true; break; } + _actions.SetCounts(_visibleEntries.Count, _entries.Count); + Invalidate(); + } + + /// 单个条目是否通过当前过滤(搜索词/类型/仅选中链路)。 + private bool MatchesFilter(Entry entry) + { + if (!string.IsNullOrEmpty(_filterType) && !string.Equals(entry.Type, _filterType, StringComparison.Ordinal)) + return false; + if (!string.IsNullOrEmpty(_filterText)) + { + string q = _filterText; + if (!ContainsText(entry.Name, q) && !ContainsText(entry.AutomationId, q) && + !ContainsText(entry.ClassName, q) && !ContainsText(entry.Item.Path, q) && + !ContainsText(entry.Type, q)) + return false; + } + if (_filterSelectedOnly && _currentEntry != null) + { + // 只保留:当前项本身 + 它的祖先 + 它的后代。 + if (entry != _currentEntry && !IsAncestorOf(entry, _currentEntry) && + !IsAncestorOf(_currentEntry, entry)) + return false; + } + return true; + } + + /// 不区分大小写的包含匹配(空文本/空查询都视为不匹配)。 + private static bool ContainsText(string text, string query) + { + return !string.IsNullOrEmpty(text) && text.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0; + } + + /// ancestor 是否是 node 的祖先(不含自身)。用 _parentOf 在内存里上溯。 + private bool IsAncestorOf(Entry ancestor, Entry node) + { + if (ancestor == null || node == null) return false; + Entry current = node; + int guard = 0; + while (guard++ < 100000) + { + Entry parent; + if (current.Item.Node == null || !_parentOf.TryGetValue(current.Item.Node, out parent) || parent == null) + return false; + if (parent == ancestor) return true; + current = parent; + } + return false; + } + + /// 条目是否属于当前选中及其祖先链。 + private bool IsInChain(Entry entry) + { + return entry.Item.Node != null ? _chainNodes.Contains(entry.Item.Node) : _chainNodes.Contains(entry); + } + + // ------------------------------------------------------------------ 选中 / 导航 + + /// 把某条目设为“当前选中”:记为当前并刷新过滤/信息面板/祖先链。 + private void SetCurrentEntry(Entry target) + { + if (target == null) return; + _currentEntry = target; + _currentNode = target.Item.Node; + _currentPath = target.Item.Path; + ApplyFilter(); // “仅选中及其祖先/后代”依赖当前项 + UpdatePanelInfo(_hoverEntry != null ? _hoverEntry : target); + } + + /// 导航/按钮统一入口:设为当前并发出 NodeSelected(外部负责选中控件树/刷新属性)。 + private void PublishSelection(Entry target) + { + if (target == null || _disposing) return; + SetCurrentEntry(target); + RaiseSelected(target, CenterOf(target)); + } + + /// 发出 NodeSelected(MainForm 收到后会在控件树里选中该节点)。 + private void RaiseSelected(Entry entry, Point screenPoint) + { + EventHandler handler = NodeSelected; + if (handler == null) return; + var args = new NodeMapSelectionEventArgs(entry.Index, entry.Item, screenPoint); + handler(this, args); + } + + /// 条目当前屏幕矩形的中心点(用于导航时的事件坐标)。 + private Point CenterOf(Entry entry) + { + Rectangle screen = entry.Offset; + screen.Offset(_anchorBounds.Left, _anchorBounds.Top); + return new Point(screen.Left + screen.Width / 2, screen.Top + screen.Height / 2); + } + + /// 「父节点」:从 items 推出的父映射上溯一层;无父时给提示。 + private void GoParent() + { + Entry start = _currentEntry ?? CurrentCandidate; + if (start == null) { _actions.SetHint("先把鼠标移到或点选一个框,再点「父节点」。"); return; } + Entry parent; + if (start.Item.Node == null || !_parentOf.TryGetValue(start.Item.Node, out parent) || parent == null) + { + _actions.SetHint("已经是根节点,没有父节点。"); + return; + } + PublishSelection(parent); + } + + /// 「上一个/下一个」:按 items 顺序(树的前序)在“可见条目”上移动。 + private void GoSibling(int direction) + { + if (_visibleEntries.Count == 0) + { + _actions.SetHint("当前没有可移动的框(可能被搜索/过滤隐藏了)。"); + return; + } + int position = _currentEntry == null ? -1 : _visibleEntries.IndexOf(_currentEntry); + if (position < 0) + { + // 当前项不在可见集合里:按原始索引朝移动方向找第一个可见项。 + int anchorIndex = _currentEntry == null ? -1 : _currentEntry.Index; + if (direction > 0) + { + position = _visibleEntries.Count - 1; + for (int i = 0; i < _visibleEntries.Count; i++) + if (_visibleEntries[i].Index > anchorIndex) { position = i; break; } + } + else + { + position = 0; + for (int i = _visibleEntries.Count - 1; i >= 0; i--) + if (_visibleEntries[i].Index < anchorIndex) { position = i; break; } + } + } + else + { + position = ((position + direction) % _visibleEntries.Count + _visibleEntries.Count) % _visibleEntries.Count; + } + PublishSelection(_visibleEntries[position]); + } + + /// 一键复制当前(鼠标下优先)框的 path。 + private void CopyCurrentPath() + { + Entry target = _hoverEntry ?? _currentEntry; + if (target == null || string.IsNullOrEmpty(target.Item.Path)) + { + _actions.SetHint("没有可复制的 path。"); + return; + } + try + { + Clipboard.SetText(target.Item.Path); + _actions.SetHint("已复制 path:" + target.Item.Path); + } + catch (Exception ex) { _actions.SetHint("复制失败:" + ex.Message); } + } + + // ------------------------------------------------------------------ 悬停 / 信息面板 + + /// 按鼠标屏幕点更新悬停项(只在内存里命中测试,且要求点在本覆盖层可见区域内)。 + private void UpdateHover(Point screenPoint) + { + Entry hover = null; + bool overPanel = _actions.Visible && _actions.Bounds.Contains(screenPoint); + if (!overPanel && _anchorBounds.Contains(screenPoint)) + { + Point local = new Point(screenPoint.X - _anchorBounds.Left, screenPoint.Y - _anchorBounds.Top); + if (Region != null && Region.IsVisible(local)) hover = HitTest(screenPoint); + } + if (hover != _hoverEntry) + { + _hoverEntry = hover; + UpdatePanelInfo(hover != null ? hover : _currentEntry); + Invalidate(); + } + } + + /// 取鼠标点下最具体(面积最小)的可见条目;没有则 null。 + private Entry HitTest(Point screenPoint) + { + Point local = new Point(screenPoint.X - _anchorBounds.Left, screenPoint.Y - _anchorBounds.Top); + Entry best = null; + long bestArea = long.MaxValue; + foreach (Entry entry in _entries) + { + if (!entry.Visible || !entry.Offset.Contains(local)) continue; + long area = (long)entry.Offset.Width * entry.Offset.Height; + if (area < bestArea) { bestArea = area; best = entry; } + } + return best; + } + + /// 把条目的类型/名称/大小/位置/路径写到侧栏信息面板(鼠标下优先)。 + private void UpdatePanelInfo(Entry entry) + { + if (entry == null) + { + _actions.SetInfo("把鼠标移到某个框上,或点框/用「父节点·上一个·下一个」选中一个节点。"); + return; + } + Rectangle screen = entry.Offset; + screen.Offset(_anchorBounds.Left, _anchorBounds.Top); + var text = new StringBuilder(); + text.Append("类型: ").Append(string.IsNullOrEmpty(entry.Type) ? "(未知)" : entry.Type); + text.Append(" 名称: ").Append(string.IsNullOrEmpty(entry.Name) ? "(无名称)" : entry.Name).Append('\n'); + text.Append("大小: ").Append(screen.Width).Append(" × ").Append(screen.Height); + text.Append(" 位置: (").Append(screen.Left).Append(", ").Append(screen.Top).Append(')').Append('\n'); + text.Append("路径: ").Append(string.IsNullOrEmpty(entry.Item.Path) ? "(无)" : entry.Item.Path); + _actions.SetInfo(text.ToString()); + } + /// 把鼠标消息映射成按键位掩码(左1/右2/中4/X1=8/X2=16),并输出按下/抬起标志。 private static int ButtonMask(int message, uint data, out bool down, out bool up) { @@ -508,13 +1029,15 @@ namespace pacs_win_uia.UI if (mask == 1 && picked != null && _pressedVersion == _version && CanIntercept(point)) { int version = _version; - var args = new NodeMapSelectionEventArgs(picked.Index, picked.Item, point); + Entry target = picked; + Point screenPoint = point; Post(delegate { if (_selectionMode && version == _version) { - EventHandler handler = NodeSelected; - if (handler != null) handler(this, args); + // 点框 = 选中该节点:覆盖层记为“当前”(加粗高亮祖先链),再通知外部。 + SetCurrentEntry(target); + RaiseSelected(target, screenPoint); } }); } @@ -599,18 +1122,73 @@ namespace pacs_win_uia.UI if (force) { _suppressedButtons = 0; _escapeSuppressed = false; } } - /// 把红框画进可见区域(用 Region 裁剪);选取模式下高亮当前候选。 + /// + /// 把框画进可见区域(用 Region 裁剪)。有当前选中时:祖先链加粗高亮、其余框变淡; + /// 选取模式下另用蓝色标出滚轮/鼠标下的候选;最后只在鼠标下的框旁画文字标签。 + /// protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (!_shown || Region == null || !WindowVisibility.IsForegroundWindow(_anchor)) return; e.Graphics.SmoothingMode = SmoothingMode.None; e.Graphics.SetClip(Region, CombineMode.Intersect); - using (var pen = new Pen(Color.Red, 1.6F)) - foreach (Entry entry in _entries) e.Graphics.DrawRectangle(pen, entry.Offset); + + bool chainMode = _chainActive; + using (var normal = new Pen(Color.Red, 1.6F)) + using (var dim = new Pen(Color.FromArgb(255, 214, 128, 128), 1.4F)) + { + foreach (Entry entry in _entries) + { + if (!entry.Visible) continue; + if (chainMode && IsInChain(entry)) continue; // 祖先链稍后统一加粗绘制 + e.Graphics.DrawRectangle(chainMode ? dim : normal, entry.Offset); + } + } + if (chainMode) + { + using (var ancestor = new Pen(Color.FromArgb(255, 255, 140, 0), 3F)) // 祖先:橙 + using (var current = new Pen(Color.DodgerBlue, 3F)) // 当前:蓝 + { + foreach (Entry entry in _entries) + { + if (!entry.Visible || !IsInChain(entry)) continue; + e.Graphics.DrawRectangle(entry == _currentEntry ? current : ancestor, entry.Offset); + } + } + } + // 选取模式下滚轮/鼠标下的候选(不与“当前”重复时再画一层蓝)。 Entry selected = CurrentCandidate; - if (_selectionMode && selected != null) + if (_selectionMode && selected != null && selected != _currentEntry) using (var pen = new Pen(Color.DodgerBlue, 3F)) e.Graphics.DrawRectangle(pen, selected.Offset); + + if (_showLabels && _hoverEntry != null && _hoverEntry.Visible) DrawHoverLabel(e.Graphics, _hoverEntry); + } + + /// 在鼠标下的框旁边画一个小标签:类型:名称 宽×高(用实色,避免与透明键混色)。 + private void DrawHoverLabel(Graphics g, Entry entry) + { + string type = string.IsNullOrEmpty(entry.Type) ? "?" : entry.Type; + string name = string.IsNullOrEmpty(entry.Name) ? "(无名称)" : entry.Name; + string text = type + ":" + name + " " + entry.Offset.Width + "×" + entry.Offset.Height; + using (var font = new Font("Microsoft YaHei UI", 8.5F)) + using (var back = new SolidBrush(Color.FromArgb(255, 255, 249, 196))) + using (var border = new Pen(Color.FromArgb(255, 160, 120, 0), 1F)) + using (var fore = new SolidBrush(Color.FromArgb(255, 30, 30, 30))) + { + SizeF size = g.MeasureString(text, font); + int width = (int)Math.Ceiling(size.Width) + 8; + int height = (int)Math.Ceiling(size.Height) + 4; + int x = entry.Offset.Right + 2; + int y = entry.Offset.Top; + if (x + width > ClientSize.Width) x = entry.Offset.Left - width - 2; // 右侧放不下改放左侧 + if (x < 0) x = 0; + if (y + height > ClientSize.Height) y = ClientSize.Height - height; + if (y < 0) y = 0; + var rect = new Rectangle(x, y, width, height); + g.FillRectangle(back, rect); + g.DrawRectangle(border, rect); + g.DrawString(text, font, fore, x + 4, y + 2); + } } /// 取窗口屏幕矩形;句柄无效、调用失败或零尺寸返回 false。 @@ -639,6 +1217,12 @@ namespace pacs_win_uia.UI ReplaceRegion(null); _entries.Clear(); _candidates.Clear(); + _entryByNode.Clear(); + _parentOf.Clear(); + _visibleEntries.Clear(); + _chainNodes.Clear(); + _currentEntry = null; + _hoverEntry = null; NodeSelected = null; SelectionModeChanged = null; MapExited = null; @@ -648,19 +1232,61 @@ namespace pacs_win_uia.UI } // Kept in the already compiled overlay source so integration requires no csproj changes. - /// 地图旁的小操作面板:切换选取模式、退出绘制、显示当前候选。 + /// + /// 地图旁的小操作面板:切换/退出选取、父节点·上一个·下一个导航、复制 path、搜索/类型过滤、 + /// 选中信息与候选显示。面板是 WS_EX_NOACTIVATE(不抢焦点、不激活),但可正常接收鼠标点击; + /// 搜索框/下拉用 NodeMapInputFocus.ForceFocus 抢键盘焦点以支持输入。 + /// internal sealed class NodeMapActionsForm : Form { + /// 类型下拉里代表“全部类型”的项。 + private const string AllTypes = "(全部类型)"; + /// “点击框获取path / 选取中”按钮。 private readonly Button _select; + /// 退出绘制按钮。 + private readonly Button _exit; + /// 父节点 / 上一个 / 下一个 导航按钮。 + private readonly Button _parent, _prev, _next; + /// 复制当前框 path 按钮。 + private readonly Button _copy; + /// 搜索框。 + private readonly TextBox _search; + /// 控件类型下拉。 + private readonly ComboBox _type; + /// “仅选中及其祖先/后代”勾选。 + private readonly CheckBox _selectedOnly; + /// “显示标签”勾选。 + private readonly CheckBox _labelsCheck; + /// 当前框信息标签(类型/名称/大小/位置/路径)。 + private readonly Label _info; /// 候选信息标签(候选 i/n 与 path)。 private readonly Label _candidate; + /// 框数量标签(可见/总数)。 + private readonly Label _counts; + /// 操作提示标签。 + private readonly Label _hint; + /// 程序性改控件时抑制事件回传,避免重入。 + private bool _suppress; + /// 请求切换选取模式。 internal event EventHandler ToggleSelection; /// 请求退出地图。 internal event EventHandler ExitMap; + /// 请求上溯父节点。 + internal event EventHandler ParentRequested; + /// 请求移动到上一个节点(树前序)。 + internal event EventHandler PrevRequested; + /// 请求移动到下一个节点(树前序)。 + internal event EventHandler NextRequested; + /// 请求复制当前框的 path。 + internal event EventHandler CopyPathRequested; + /// 搜索词/类型/仅选中发生变化。 + internal event EventHandler FilterChanged; + /// “显示标签”勾选发生变化。 + internal event EventHandler LabelsChanged; - /// 构建面板控件并接线按钮点击(选取切换失败时在标签上提示)。 + /// 构建面板控件并接线(选取切换失败时在提示里说明)。 internal NodeMapActionsForm() { FormBorderStyle = FormBorderStyle.None; @@ -668,25 +1294,85 @@ namespace pacs_win_uia.UI StartPosition = FormStartPosition.Manual; AutoScaleMode = AutoScaleMode.None; TopMost = true; - ClientSize = new Size(170, 112); + ClientSize = new Size(296, 436); BackColor = SystemColors.Control; - _select = new Button { Text = "点击框获取path", Bounds = new Rectangle(5, 5, 160, 32), TabStop = false }; - var exit = new Button { Text = "退出绘制", Bounds = new Rectangle(5, 41, 160, 30), TabStop = false }; - _candidate = new Label { Bounds = new Rectangle(5, 76, 160, 32), AutoEllipsis = true, Text = "选取后滚轮切换重叠节点" }; + + _select = new Button { Text = "点击框获取path", Bounds = new Rectangle(6, 6, 284, 30), TabStop = false }; + _exit = new Button { Text = "退出绘制", Bounds = new Rectangle(6, 40, 284, 26), TabStop = false }; + _parent = new Button { Text = "父节点", Bounds = new Rectangle(6, 72, 90, 26), TabStop = false }; + _prev = new Button { Text = "上一个", Bounds = new Rectangle(100, 72, 90, 26), TabStop = false }; + _next = new Button { Text = "下一个", Bounds = new Rectangle(194, 72, 96, 26), TabStop = false }; + _copy = new Button { Text = "复制当前框 Path", Bounds = new Rectangle(6, 102, 284, 26), TabStop = false }; + var searchLabel = new Label { Text = "搜索", Bounds = new Rectangle(6, 134, 38, 24), TextAlign = ContentAlignment.MiddleLeft }; + _search = new TextBox { Bounds = new Rectangle(46, 134, 244, 24) }; + _type = new ComboBox { Bounds = new Rectangle(6, 164, 284, 24), DropDownStyle = ComboBoxStyle.DropDownList }; + _type.Items.Add(AllTypes); + _type.SelectedIndex = 0; + _selectedOnly = new CheckBox { Text = "仅选中及其祖先/后代", Bounds = new Rectangle(4, 192, 182, 24) }; + _labelsCheck = new CheckBox { Text = "显示标签", Bounds = new Rectangle(190, 192, 100, 24), Checked = true }; + _info = new Label { Bounds = new Rectangle(6, 220, 284, 90), BorderStyle = BorderStyle.FixedSingle, + AutoEllipsis = true, Text = "把鼠标移到某个框上,或点框/用「父节点·上一个·下一个」选中一个节点。" }; + _candidate = new Label { Bounds = new Rectangle(6, 314, 284, 44), AutoEllipsis = true, Text = "选取后滚轮切换重叠节点" }; + _counts = new Label { Bounds = new Rectangle(6, 360, 284, 18), Text = "框: 0 / 0" }; + _hint = new Label { Bounds = new Rectangle(6, 380, 284, 50), AutoEllipsis = true, Text = "" }; + _select.Click += delegate { - try - { - EventHandler handler = ToggleSelection; - if (handler != null) handler(this, EventArgs.Empty); - } - catch (Win32Exception) { _candidate.Text = "钩子安装失败,未进入选取"; } + try { Raise(ToggleSelection); } + catch (Win32Exception) { SetHint("钩子安装失败,未进入选取。"); } }; - exit.Click += delegate { EventHandler handler = ExitMap; if (handler != null) handler(this, EventArgs.Empty); }; + _exit.Click += delegate { Raise(ExitMap); }; + _parent.Click += delegate { Raise(ParentRequested); }; + _prev.Click += delegate { Raise(PrevRequested); }; + _next.Click += delegate { Raise(NextRequested); }; + _copy.Click += delegate { Raise(CopyPathRequested); }; + // 搜索框/下拉在 NOACTIVATE 窗口上默认拿不到键盘焦点,点按时强制聚焦(不激活本窗口)。 + _search.MouseDown += delegate { NodeMapInputFocus.ForceFocus(_search); }; + _type.MouseDown += delegate { NodeMapInputFocus.ForceFocus(_type); }; + _search.TextChanged += delegate { if (!_suppress) Raise(FilterChanged); }; + _type.SelectedIndexChanged += delegate { if (!_suppress) Raise(FilterChanged); }; + _selectedOnly.CheckedChanged += delegate { if (!_suppress) Raise(FilterChanged); }; + _labelsCheck.CheckedChanged += delegate { if (!_suppress) Raise(LabelsChanged); }; + Controls.Add(_select); - Controls.Add(exit); + Controls.Add(_exit); + Controls.Add(_parent); + Controls.Add(_prev); + Controls.Add(_next); + Controls.Add(_copy); + Controls.Add(searchLabel); + Controls.Add(_search); + Controls.Add(_type); + Controls.Add(_selectedOnly); + Controls.Add(_labelsCheck); + Controls.Add(_info); Controls.Add(_candidate); + Controls.Add(_counts); + Controls.Add(_hint); } + + /// 安全地触发事件(无订阅者则忽略)。 + private void Raise(EventHandler handler) + { + if (handler != null) handler(this, EventArgs.Empty); + } + + /// 搜索词。 + internal string SearchText { get { return _search.Text; } } + /// 选中的类型(“(全部类型)”返回空串表示不过滤)。 + internal string SelectedType + { + get + { + var selected = _type.SelectedItem as string; + return string.IsNullOrEmpty(selected) || selected == AllTypes ? string.Empty : selected; + } + } + /// 是否只保留当前选中及其祖先/后代。 + internal bool SelectedOnly { get { return _selectedOnly.Checked; } } + /// 是否显示悬停标签。 + internal bool LabelsChecked { get { return _labelsCheck.Checked; } } + /// 显示时不激活窗口(面板可被点击但不抢键盘焦点)。 protected override bool ShowWithoutActivation { get { return true; } } /// 扩展样式:工具窗口、不激活(但可接收鼠标点击)。 @@ -733,5 +1419,68 @@ namespace pacs_win_uia.UI "候选 " + index + "/" + count + " · 滚轮切换\r\n" + (path ?? "点击返回节点索引"); if (_candidate.Text != text) _candidate.Text = text; } + /// 刷新框数量标签(可见 / 总数)。 + internal void SetCounts(int visible, int total) + { + string text = "框: " + visible + " / " + total; + if (_counts.Text != text) _counts.Text = text; + } + /// 刷新当前框信息标签。 + internal void SetInfo(string text) + { + if (text == null) text = string.Empty; + if (_info.Text != text) _info.Text = text; + } + /// 刷新操作提示。 + internal void SetHint(string text) + { + if (text == null) text = string.Empty; + if (_hint.Text != text) _hint.Text = text; + } + /// 外部同步“显示标签”勾选(不回调 LabelsChanged)。 + internal void SetLabels(bool on) + { + if (_labelsCheck.Checked == on) return; + _suppress = true; + try { _labelsCheck.Checked = on; } + finally { _suppress = false; } + } + /// 用 items 里收集到的类型刷新下拉(集合不变则不重建,避免闪烁/打断下拉)。 + internal void SetTypes(IList types, string keep) + { + var desired = new List(); + desired.Add(AllTypes); + if (types != null) foreach (string type in types) if (!string.IsNullOrEmpty(type)) desired.Add(type); + + bool same = _type.Items.Count == desired.Count; + for (int i = 0; same && i < desired.Count; i++) + same = string.Equals(_type.Items[i] as string, desired[i], StringComparison.Ordinal); + + string before = SelectedType; + _suppress = true; + try + { + if (!same) + { + _type.BeginUpdate(); + try + { + _type.Items.Clear(); + foreach (string item in desired) _type.Items.Add(item); + } + finally { _type.EndUpdate(); } + } + int index = 0; + if (!string.IsNullOrEmpty(keep)) + { + int found = _type.Items.IndexOf(keep); + if (found >= 0) index = found; + } + if (_type.SelectedIndex != index) _type.SelectedIndex = index; + } + finally { _suppress = false; } + // 选中的类型被程序性改掉(例如该类型已不在 items 里)时,通知覆盖层同步过滤状态。 + if (!string.Equals(before, SelectedType, StringComparison.Ordinal)) Raise(FilterChanged); + } } } diff --git a/tests/regression/ValueKeyTests.cs b/tests/regression/ValueKeyTests.cs index fa64898..df80dce 100644 --- a/tests/regression/ValueKeyTests.cs +++ b/tests/regression/ValueKeyTests.cs @@ -83,7 +83,8 @@ namespace PacsWinUia.RegressionTests { foreach (string key in new[] { - ControlValueKeys.ListRowCount, ControlValueKeys.ListColumnCount, ControlValueKeys.ListSelectedCount + ControlValueKeys.ListRowCount, ControlValueKeys.ListColumnCount, + ControlValueKeys.ListSelectedCount, ControlValueKeys.SelectedRowText }) { Check.True(ControlValueKeys.For(ControlSourcePreference.Uia).Contains(key), @@ -92,6 +93,7 @@ namespace PacsWinUia.RegressionTests Check.Equal("列表行数", ControlValueKeys.ListRowCount, "Row count key name"); Check.Equal("列表选中项数", ControlValueKeys.ListSelectedCount, "Selected count key name"); + Check.Equal("选中行文本", ControlValueKeys.SelectedRowText, "Selected row text key name"); } private static void TextContentKeyOffered()