新增跨来源取值键「文本内容」,修好富文本/输入框读不到内容

问题:富文本(RichTextBox、Chromium/CEF、UWP 文本框)的 UIA Name 往往是通用标题
(实测夹具里是 "RichEdit Control"),真正的内容只在 ValuePattern/TextPattern 里;
而新增监控项时默认 ValueKey 是 Name,于是读回来的是标题而不是内容。

- ControlValueKeys 新增跨来源键「文本内容」:UIA 按 Value → Text → Name 顺序取,
  MSAA = accValue → accName,Win32 = 窗口标题;三种都取不到才报错并说明各自原因
- 新增/拾取控件时默认 ValueKey 改为「文本内容」(旧条目不受影响,仍按各自保存的键读)
- 「文本内容」加进三个来源的可选键列表,监控列表下拉里能直接选
- 夹具新增多行富文本 FixtureRichText(内容只在 Value/Text 里)
- 回归新增 ValueKeyTests(键表、Name 兜底、默认键),共 27/27 通过

实测(跨进程,目标为独立进程里的夹具窗口):
- 文本框 文本内容="可编辑文本";富文本 文本内容="富文本第一行\r富文本第二行\r";
  按钮(无 Value/Text 模式)自动退回 Name="测试按钮"
- 拾取点在两个控件上都精确命中 Edit / Document,且能在窗口树里找到同一节点
- 无界面读取端到端:2 条配置(//Document[...]、//Edit[...] + 文本内容)全部命中并取到值
This commit is contained in:
zimoyin
2026-10-13 16:22:03 +08:00
parent 44fb305dc4
commit 529f7910a1
9 changed files with 187 additions and 6 deletions
+1
View File
@@ -81,6 +81,7 @@ MainForm(UI/MainForm.cs) 三栏主界面:窗口列表 | 控件树/列
- **不要"取第一个匹配"**:不确定就报错,让人重新拾取。 - **不要"取第一个匹配"**:不确定就报错,让人重新拾取。
- **PropertyGrid 正在编辑时不要去 rebind**:会打断用户输入,`MainForm` 里有专门判断。 - **PropertyGrid 正在编辑时不要去 rebind**:会打断用户输入,`MainForm` 里有专门判断。
- **悬浮条的"名称"不是定位条件**:定位条件是进程名/窗口类/标题关键词 + 可选导入 XPath。 - **悬浮条的"名称"不是定位条件**:定位条件是进程名/窗口类/标题关键词 + 可选导入 XPath。
- **输入框/富文本的内容常常不在 `Name` 里**:WinForms 文本框的 `Name` 就是内容,但 WinForms 富文本、Chromium/CEF、UWP 文本框的 `Name` 可能是通用标题(例如 `RichEdit Control`),内容只在 `Value`/`Text` 模式里。取内容请用跨来源键 **`文本内容`**(顺序 Value → Text → Name,MSAA 侧 = accValue → accName,Win32 侧 = 窗口标题);新增/拾取控件时它已经是默认的 valueKey。
- **旧路径格式已停用**:`[Uia] A[id] > B:name`、`Type[id]` 之类不再执行,只保留给人工编辑修正。 - **旧路径格式已停用**:`[Uia] A[id] > B:name`、`Type[id]` 之类不再执行,只保留给人工编辑修正。
- **本工具自己的窗口不算遮挡**:主界面/设置窗口压住目标不影响悬浮条显示(否则在设置页里根本测不了)。 - **本工具自己的窗口不算遮挡**:主界面/设置窗口压住目标不影响悬浮条显示(否则在设置页里根本测不了)。
- **bin\Debug 的 exe 被运行时锁定**:改完代码要编译时,先关掉正在运行的工具,或编译到别的输出目录。 - **bin\Debug 的 exe 被运行时锁定**:改完代码要编译时,先关掉正在运行的工具,或编译到别的输出目录。
+15 -3
View File
@@ -157,6 +157,15 @@ namespace pacs_win_uia.Models
public static class ControlValueKeys public static class ControlValueKeys
{ {
// Selected:跨来源键——该控件当前是否处于选中状态。 // Selected:跨来源键——该控件当前是否处于选中状态。
/// <summary>
/// 跨来源键:这个控件的"内容文本"。
/// 很多控件的内容不在 Name 里——输入框/富文本的 Name 可能是通用标题(例如 RichEdit Control),
/// 内容只存在于 ValuePattern/TextPattern;而另一类客户端(如 WinForms TextBox、部分自绘界面)
/// 又把内容直接放在 Name 里。这个键按 Value → Text → Name 顺序取第一个能用的值,
/// 是新增文本类控件时的推荐默认值。
/// </summary>
public const string TextContent = "文本内容";
/// <summary>Cross-source key: is this control the selected one.</summary> /// <summary>Cross-source key: is this control the selected one.</summary>
public const string Selected = "选中状态"; public const string Selected = "选中状态";
@@ -174,7 +183,8 @@ namespace pacs_win_uia.Models
// Uia:UIA 来源可读取的属性键列表。 // Uia:UIA 来源可读取的属性键列表。
public static readonly IList<string> Uia = new List<string> public static readonly IList<string> Uia = new List<string>
{ {
"Name", "AutomationId", "ControlType", "ClassName", "FrameworkId", // 文本内容排在最前:它是文本类控件最常用的取值键。
TextContent, "Name", "AutomationId", "ControlType", "ClassName", "FrameworkId",
"RuntimeId", "IsEnabled", "IsOffscreen", "BoundingRectangle", "RuntimeId", "IsEnabled", "IsOffscreen", "BoundingRectangle",
"Value", "Text", Selected, "IsSelected", Focused, "HasKeyboardFocus" "Value", "Text", Selected, "IsSelected", Focused, "HasKeyboardFocus"
}; };
@@ -182,14 +192,16 @@ namespace pacs_win_uia.Models
// Msaa:MSAA 来源可读取的属性键列表。 // Msaa:MSAA 来源可读取的属性键列表。
public static readonly IList<string> Msaa = new List<string> public static readonly IList<string> Msaa = new List<string>
{ {
"accName", "accValue", "accRole", "accState", "accDescription", "accDefaultAction", "PathKey", // 跨来源键在三个来源里都可以选(文本内容在 MSAA 侧 = accValue → accName)。
TextContent, "accName", "accValue", "accRole", "accState", "accDescription", "accDefaultAction", "PathKey",
Selected, Focused Selected, Focused
}; };
// Win32:Win32 来源可读取的属性键列表。 // Win32:Win32 来源可读取的属性键列表。
public static readonly IList<string> Win32 = new List<string> public static readonly IList<string> Win32 = new List<string>
{ {
"窗口标题", "类名", "HWND", "窗口矩形", "客户区矩形", "可见", "最小化", "进程名", "PID", Focused // 跨来源键在三个来源里都可以选(文本内容在 Win32 侧 = 窗口标题)。
TextContent, "窗口标题", "类名", "HWND", "窗口矩形", "客户区矩形", "可见", "最小化", "进程名", "PID", Focused
}; };
// For:按来源偏好给出建议键;Auto 返回三来源的并集,末尾附加 OCR 文本键。 // For:按来源偏好给出建议键;Auto 返回三来源的并集,末尾附加 OCR 文本键。
@@ -194,7 +194,12 @@ namespace pacs_win_uia.Services
/// <summary>Captures the same canonical RawView window tree used by resolution.</summary> /// <summary>Captures the same canonical RawView window tree used by resolution.</summary>
public ControlLocatorBuildResult BuildFromUia(UiaElementInfo element, NativeWindowInfo window) public ControlLocatorBuildResult BuildFromUia(UiaElementInfo element, NativeWindowInfo window)
{ {
var failure = new ControlLocatorBuildResult { Source = ControlSourcePreference.Uia, ValueKey = "Name" }; // 默认取"文本内容"(Value → Text → Name):输入框/富文本的内容常常不在 Name 里。
var failure = new ControlLocatorBuildResult
{
Source = ControlSourcePreference.Uia,
ValueKey = ControlValueKeys.TextContent
};
ApplyWindowFields(failure, window); ApplyWindowFields(failure, window);
if (element == null || element.Element == null || window == null) if (element == null || element.Element == null || window == null)
{ {
@@ -279,7 +284,7 @@ namespace pacs_win_uia.Services
break; break;
default: default:
if (node.Uia == null) { result.Note = "节点缺少 UIA 数据。"; return result; } if (node.Uia == null) { result.Note = "节点缺少 UIA 数据。"; return result; }
result.ValueKey = "Name"; result.ValueKey = ControlValueKeys.TextContent;
result.RuntimeId = node.Uia.RuntimeId; result.RuntimeId = node.Uia.RuntimeId;
result.Value = node.Uia.Name; result.Value = node.Uia.Name;
break; break;
@@ -191,6 +191,9 @@ namespace pacs_win_uia.Services
switch (key) switch (key)
{ {
// 文本内容:Value → Text → Name,取第一个能用的;三者都取不到才报错。
case ControlValueKeys.TextContent:
return TryReadUiaTextContent(info, options, out value, out error);
case "Name": case "Name":
value = info.Name; value = info.Name;
break; break;
@@ -245,6 +248,43 @@ namespace pacs_win_uia.Services
return true; return true;
} }
/// <summary>
/// 读取"这个控件的内容文本"。顺序:ValuePattern → TextPattern → 快照 Name。
/// 这样输入框(内容在 Value)、富文本(内容在 Text)和把内容放在 Name 里的客户端都能拿到值。
/// 只有三种都拿不到才算失败,错误信息里会说明各自的原因。
/// </summary>
// 文本内容:Value → Text → Name,兼容"内容在 Name 里"和"内容在模式里"两类客户端。
private static bool TryReadUiaTextContent(UiaElementInfo info, ListReadOptions options,
out string value, out string error)
{
value = null;
error = null;
var failures = new List<string>();
foreach (string key in new[] { "Value", "Text" })
{
string candidate;
string keyError;
if (TryReadUiaPatternValue(info, key, options, out candidate, out keyError) &&
!string.IsNullOrEmpty(candidate))
{
value = candidate;
return true;
}
failures.Add(key + ":" + (keyError ?? "为空"));
}
if (!string.IsNullOrEmpty(info == null ? null : info.Name))
{
value = info.Name;
return true;
}
error = "该控件的内容文本取不到(" + string.Join(";", failures.ToArray()) + ";Name 也为空)。";
return false;
}
/// <summary>Value/Text need live pattern calls, so they are only attempted when asked for.</summary> /// <summary>Value/Text need live pattern calls, so they are only attempted when asked for.</summary>
// Value/Text 需要实时模式调用,仅在明确请求时才尝试:Value 用 ValuePattern,Text 用 TextPattern(按 MaxTextLength 有界读取)。 // Value/Text 需要实时模式调用,仅在明确请求时才尝试:Value 用 ValuePattern,Text 用 TextPattern(按 MaxTextLength 有界读取)。
private static bool TryReadUiaPatternValue(UiaElementInfo info, string key, ListReadOptions options, out string value, out string error) private static bool TryReadUiaPatternValue(UiaElementInfo info, string key, ListReadOptions options, out string value, out string error)
@@ -421,6 +461,10 @@ namespace pacs_win_uia.Services
switch (key) switch (key)
{ {
// 跨来源键「文本内容」:MSAA 侧取 accValue,没有就退回 accName。
case ControlValueKeys.TextContent:
value = !string.IsNullOrEmpty(info.Value) ? info.Value : info.Name;
break;
case "accName": case "accName":
value = info.Name; value = info.Name;
break; break;
@@ -475,6 +519,10 @@ namespace pacs_win_uia.Services
switch (key) switch (key)
{ {
// 跨来源键「文本内容」:Win32 侧能当"内容"用的就是窗口标题。
case ControlValueKeys.TextContent:
value = info.Title;
break;
case "窗口标题": case "窗口标题":
value = info.Title; value = info.Title;
break; break;
+1 -1
View File
@@ -44,7 +44,7 @@ tests\run-fixture.cmd Release :: Release
| 窗口 | 内容 | | 窗口 | 内容 |
| --- | --- | | --- | --- |
| `UIA 测试夹具` | 「控件」页:按钮、文本框、复选框、单选、下拉、两列 ListView、TreeView、状态标签;「表格」页:5 行 × 3 列 DataGridView;「嵌套」页:三层嵌套容器里的 ListBox | | `UIA 测试夹具` | 「控件」页:按钮、文本框、**富文本(FixtureRichText,内容只在 Value/Text 里,Name 是 "RichEdit Control")**、复选框、单选、下拉、两列 ListView、TreeView、状态标签;「表格」页:5 行 × 3 列 DataGridView;「嵌套」页:三层嵌套容器里的 ListBox |
| `UIA 测试夹具 - 第二个窗口` | 一个按钮(测试"选哪个窗口"、窗口列表分组与匹配) | | `UIA 测试夹具 - 第二个窗口` | 一个按钮(测试"选哪个窗口"、窗口列表分组与匹配) |
两个窗口的**标题与类名都固定**,所以保存的监控条目、悬浮条显示条件可以长期复用。 两个窗口的**标题与类名都固定**,所以保存的监控条目、悬浮条显示条件可以长期复用。
+1
View File
@@ -52,6 +52,7 @@ namespace PacsWinUia.RegressionTests
FloatingConditionsTests.Register(tests); FloatingConditionsTests.Register(tests);
SettingsComboBoxTests.Register(tests); SettingsComboBoxTests.Register(tests);
WindowVisibilityTests.Register(tests); WindowVisibilityTests.Register(tests);
ValueKeyTests.Register(tests);
int passed = 0; int passed = 0;
// 逐个执行登记的用例:通过则 PASS 并累加,抛异常则 FAIL 并打印完整异常。 // 逐个执行登记的用例:通过则 PASS 并累加,抛异常则 FAIL 并打印完整异常。
foreach (var test in tests) foreach (var test in tests)
+1
View File
@@ -45,6 +45,7 @@
<Compile Include="FloatingConditionsTests.cs" /> <Compile Include="FloatingConditionsTests.cs" />
<Compile Include="SettingsComboBoxTests.cs" /> <Compile Include="SettingsComboBoxTests.cs" />
<Compile Include="WindowVisibilityTests.cs" /> <Compile Include="WindowVisibilityTests.cs" />
<Compile Include="ValueKeyTests.cs" />
<!-- 把主项目的 ControlTreeReconciler 以链接方式编译进测试程序集(部分内部成员需要同程序集可见)。 --> <!-- 把主项目的 ControlTreeReconciler 以链接方式编译进测试程序集(部分内部成员需要同程序集可见)。 -->
<Compile Include="..\..\src\pacs_win_uia\UI\ControlTreeReconciler.cs"><Link>ControlTreeReconciler.cs</Link></Compile> <Compile Include="..\..\src\pacs_win_uia\UI\ControlTreeReconciler.cs"><Link>ControlTreeReconciler.cs</Link></Compile>
</ItemGroup> </ItemGroup>
+102
View File
@@ -0,0 +1,102 @@
// =====================================================================================
// ValueKeyTests —— 取值键(尤其是新增的跨来源键「文本内容」)的回归。
//
// 覆盖范围:
// · ControlValueKeys 必须暴露「文本内容」,并且它是 UIA/Auto 的第一个推荐键;
// · ControlValueReader 对「文本内容」的降级顺序:Value → Text → Name
// (快照没有可用的 UIA 元素时,也应该退回 Name,而不是直接报错——很多客户端
// 就是把输入框/富文本的内容放在 Name 里);
// · 新增监控项/拾取控件时默认保存的 ValueKey 是「文本内容」。
//
// 为什么这样测:全部用内存里的 UiaElementInfo 快照 + 内存控件树,不调用 UIA、
// 不启动目标程序,结果稳定(真正跨进程的取值验证见 tests/uia-fixture 手工清单)。
//
// 新增用例:加到 Register(...) 列表并实现 private static void 方法,断言走 Check.*。
// =====================================================================================
using System;
using System.Collections.Generic;
using pacs_win_uia.Models;
using pacs_win_uia.Services;
namespace PacsWinUia.RegressionTests
{
internal static class ValueKeyTests
{
public static void Register(IList<KeyValuePair<string, Action>> tests)
{
// 防:文本内容键被移除/排到后面,导致监控列表默认又去读 Name。
tests.Add(new KeyValuePair<string, Action>("Text content key is offered first for UIA", TextContentKeyOffered));
// 防:内容在 Name 里的客户端(WinForms 输入框、自绘界面)读不到值。
tests.Add(new KeyValuePair<string, Action>("Text content falls back to the snapshot Name", TextContentFallsBackToName));
// 防:新增控件默认 ValueKey 回到 Name;富文本这类控件会读到 "RichEdit Control"。
tests.Add(new KeyValuePair<string, Action>("New monitor entries default to the text content key", BuilderDefaultsToTextContent));
}
private static void TextContentKeyOffered()
{
Check.Equal("文本内容", ControlValueKeys.TextContent, "Text content key name");
Check.Equal(ControlValueKeys.TextContent, ControlValueKeys.Uia[0], "Text content should be the first UIA key");
Check.True(ControlValueKeys.For(ControlSourcePreference.Uia).Contains(ControlValueKeys.TextContent),
"UIA keys missing the text content key");
Check.True(ControlValueKeys.For(ControlSourcePreference.Auto).Contains(ControlValueKeys.TextContent),
"Auto keys missing the text content key");
Check.True(ControlValueKeys.ForSource(ControlTreeSource.Uia).Contains(ControlValueKeys.TextContent),
"Source-based keys missing the text content key");
}
private static void TextContentFallsBackToName()
{
// 没有 Element(快照已脱离元素):模式调用不可用,必须退回 Name。
var node = new ControlTreeNode
{
Source = ControlTreeSource.Uia,
Uia = new UiaElementInfo { ControlType = "ControlType.Edit", Name = "内容在 Name 里", IsAvailable = true }
};
string value;
string error;
Check.True(ControlValueReader.TryRead(node, ControlValueKeys.TextContent,
new ListReadOptions(), null, out value, out error), "Text content failed without an element: " + error);
Check.Equal("内容在 Name 里", value, "Text content did not fall back to Name");
// Name 也为空 → 明确失败,并说明 Value/Text/Name 都取不到。
var empty = new ControlTreeNode
{
Source = ControlTreeSource.Uia,
Uia = new UiaElementInfo { ControlType = "ControlType.Edit", IsAvailable = true }
};
Check.True(!ControlValueReader.TryRead(empty, ControlValueKeys.TextContent,
new ListReadOptions(), null, out value, out error), "Empty control should fail");
Check.True(error != null && error.Contains("Name"),
"Failure message should mention the inspected sources: " + error);
}
private static void BuilderDefaultsToTextContent()
{
var root = new ControlTreeNode
{
Source = ControlTreeSource.Uia,
Uia = new UiaElementInfo { ControlType = "ControlType.Window", Name = "窗口", ClassName = "Host", IsAvailable = true }
};
var rich = new ControlTreeNode
{
Source = ControlTreeSource.Uia,
// 富文本的典型样子:Name 是通用标题,真正的内容只在 Value/Text 模式里。
Uia = new UiaElementInfo
{
ControlType = "ControlType.Document", Name = "RichEdit Control",
AutomationId = "FixtureRichText", ClassName = "RICHEDIT50W", IsAvailable = true
}
};
root.Children.Add(rich);
ControlPath.PreparePaths(root);
var window = new NativeWindowInfo(IntPtr.Zero) { ProcessName = "fixture", ClassName = "Host", Title = "夹具" };
ControlLocatorBuildResult built = new ControlLocatorBuilder().BuildFromTree(root, rich, window);
Check.Equal(ControlValueKeys.TextContent, built.ValueKey, "Builder default value key must be the text content key");
Check.True(built.IsComplete, "Builder path incomplete: " + built.Note);
Check.True(built.DisplayPath.IndexOf("@AutomationId='FixtureRichText'", StringComparison.Ordinal) >= 0,
"Builder path should identify the text control: " + built.DisplayPath);
}
}
}
+11
View File
@@ -34,6 +34,7 @@ namespace UiaFixture
{ {
private readonly Label _status; private readonly Label _status;
private readonly TextBox _input; private readonly TextBox _input;
private readonly RichTextBox _rich;
private readonly CheckBox _check; private readonly CheckBox _check;
private readonly ComboBox _combo; private readonly ComboBox _combo;
private readonly TreeView _tree; private readonly TreeView _tree;
@@ -73,6 +74,15 @@ namespace UiaFixture
}; };
_input.TextChanged += delegate { SetStatus("文本框内容已改为:" + _input.Text); }; _input.TextChanged += delegate { SetStatus("文本框内容已改为:" + _input.Text); };
// 多行富文本:内容较长,用来验证"内容在 Name/Value/Text 里"的取值与拾取定位。
_rich = new RichTextBox
{
Name = "FixtureRichText",
Text = "富文本第一行" + Environment.NewLine + "富文本第二行",
Location = new Point(380, 14),
Size = new Size(240, 60)
};
_check = new CheckBox _check = new CheckBox
{ {
Text = "启用选项", Text = "启用选项",
@@ -138,6 +148,7 @@ namespace UiaFixture
panel.Controls.Add(button); panel.Controls.Add(button);
panel.Controls.Add(_input); panel.Controls.Add(_input);
panel.Controls.Add(_rich);
panel.Controls.Add(_check); panel.Controls.Add(_check);
panel.Controls.Add(radioA); panel.Controls.Add(radioA);
panel.Controls.Add(radioB); panel.Controls.Add(radioB);