Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS UI Automation - How to get text from ControlType.text

I have a small windows application that has a series of labels on it. This application will be globalized and there is a possibility that the text on these labels might get truncated. I am trying to automate to identify truncated text on these labels.

For other controls, I can use TextPattern.Pattern through which I can find the visible text and the actual text inside the control. But for the labels (ControlType.text) the TextPattern is not supported. How do I find the visible text for these lables using UI automation.

Here is the code I tried. If I pass control type as Document it works. But with Text control type it gives a unsupported pattern exception.

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;
        }
like image 469
Virus Avatar asked Nov 20 '25 05:11

Virus


1 Answers

You should be able to simply use element.Current.Name (element being the instance of AutomationElement for the label).

Here is an example of UISpy retrieving the text for a label:

enter image description here

like image 63
Simon Mourier Avatar answered Nov 21 '25 18:11

Simon Mourier