【问题标题】:MS UI Automation - How to get text from ControlType.textMS UI 自动化 - 如何从 ControlType.text 获取文本
【发布时间】:2015-12-05 08:00:02
【问题描述】:

我有一个小型 Windows 应用程序,上面有一系列标签。此应用程序将被全球化,并且这些标签上的文本可能会被截断。我正在尝试自动识别这些标签上的截断文本。

对于其他控件,我可以使用TextPattern.Pattern,通过它我可以找到控件内部的可见文本和实际文本。但是对于标签 (ControlType.text),不支持 TextPattern。如何使用 UI 自动化找到这些标签的可见文本。

这是我尝试过的代码。如果我将控件类型作为 Document 传递,它可以工作。但是对于 Text 控件类型,它会给出不支持的模式异常。

private String TextFromSelection(AutomationElement target, Int32 length)
        {
            // Specify the control type we're looking for, in this case 'Document'
            PropertyCondition cond = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text);

            // target --> The root AutomationElement.
            AutomationElement textProvider = target.FindFirst(TreeScope.Descendants, cond);

            TextPattern textpatternPattern = textProvider.GetCurrentPattern(TextPattern.Pattern) as TextPattern;

            if (textpatternPattern == null)
            {
                Console.WriteLine("Root element does not contain a descendant that supports TextPattern.");
                return null;
            }


            var test = textpatternPattern.DocumentRange.GetText(-1).TrimEnd('\r');

            var tpr = textpatternPattern.GetVisibleRanges();
            var txt = tpr[0].GetText(-1);

            return txt;
        }

【问题讨论】:

    标签: c# automation ui-automation microsoft-ui-automation


    【解决方案1】:

    标签元素是否支持文本模式将受所使用的 UI 框架的影响。例如,Win32 Run dlg 中的标签不支持文本模式,但 Windows 10 XAML 计算器中的标签支持。下图显示了 Inspect SDK 工具报告“尚无历史记录”标签支持文本模式。

    请务必注意,当您调用 IUIAutomationTextPattern::GetVisibleRanges() 时,UI 框架(或应用程序,如果应用程序直接实现 UIA 文本模式)是否在返回给您的数据中包含截断的文本,取决于框架(或应用程序)本身。例如,在 Windows 10 上运行的写字板不包括被剪裁出来的文本,但 Word 2013 会返回被剪裁的文本。

    谢谢,

    男人

    【讨论】:

      【解决方案2】:

      您应该能够简单地使用element.Current.Name(元素是标签的AutomationElement实例)。

      这是 UISpy 检索标签文本的示例:

      【讨论】:

      • 是的,没错。但这给了我整个文本,而不管什么文本是可见的。如果文本被截断,我只想获取可见文本。
      • 我不认为这很容易
      • 好的!这适用于编辑和文档等其他控件。我们可以很容易地只获得可见的文本。但是对于标签控制似乎没有办法。
      猜你喜欢
      • 2015-12-15
      • 1970-01-01
      • 2016-07-29
      • 2010-10-05
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 2018-08-05
      相关资源
      最近更新 更多