【发布时间】:2019-03-06 15:42:13
【问题描述】:
背景信息
我正在开发一个 Windows Speech-To-Text 应用程序。
识别语音后,应将文本插入当前具有键盘焦点的文本框中(Think Word/Firefox/其他应用程序)。 要插入我当前使用的文本InputSimulatorPlus。
在插入文本时,重要的是要对识别的文本进行格式化以适应周围的文本,例如:
- 标点符号后的大写字母
- 第一个字母不在标点符号之后时小写
- 新行首字母大写
- 标点符号后的空格
等等
问题
为了能够格式化文本,我需要文本和插入符号位置。
目前我一直在使用UI Automation NuGet Package 和Text Pattern。 这适用于所有支持文本模式的文本框,但很多程序不支持文本模式。
策略问题:我应该使用 UI 自动化以外的其他方法吗?
我注意到很多我想支持的应用程序不支持文本模式,但支持值模式或传统 IAccessible 模式(Microsoft Active Accessibility)。
我一直在研究使用Value Pattern 并且可以获取文本框的文本,但不是插入符号的位置。
using System.Windows.Automation;
using System.Windows.Automation.Text;
...
AutomationElement automationElement = AutomationElement.FocusedElement;
var elements = automationElement.FindAll(TreeScope.Element,
new AndCondition(
new PropertyCondition(AutomationElement.HasKeyboardFocusProperty, true),
new PropertyCondition(AutomationElement.IsValuePatternAvailableProperty, true)));
foreach (AutomationElement element in elements)
{
if (element.GetCurrentPattern(ValuePattern.Pattern) is ValuePattern valuePattern)
{
var text = valuePattern.Current.Value;
var caret = ? //How to get caret position?
Console.WriteLine($"Caret: {caret}, Text: {text}");
return (text,caret);
}
}
我也一直在研究使用Legacy IAccessible Pattern 并且可以获取文本框的文本,但不是插入符号的位置。
using System.Windows.Automation;
using System.Windows.Automation.Text;
...
AutomationElement automationElement = AutomationElement.FocusedElement;
var elements = automationElement.FindAll(TreeScope.Element,
new AndCondition(
new PropertyCondition(AutomationElement.HasKeyboardFocusProperty, true),
new PropertyCondition(AutomationElement.IsLegacyIAccessiblePatternAvailableProperty, true)));
foreach (AutomationElement element in elements)
{
if (element.GetCurrentPattern(LegacyIAccessiblePattern.Pattern) is LegacyIAccessiblePattern legazyAccessiblePattern)
{
var text = legazyAccessiblePattern.Current.Value;
var caret = ? //How to get caret position?
Console.WriteLine($"Caret: {caret}, Text: {text}");
return (text,caret);
}
}
主要问题:如何使用 UI 自动化获取给定文本框的插入符号位置?
附:我知道这永远不会适用于所有应用程序,但如果它可以适用于大多数普通应用程序,那就太棒了。
【问题讨论】:
标签: c# .net windows ui-automation