[ACCEPTED]-C# System.Windows.Automation get element text-ui-automation

Accepted answer
Score: 18

That sample is showing you how to get text attributes, i.e. information 26 about the display of the text in the UI, not 25 the actual displayed text. Getting all the 24 actual displayed text for a general application 23 is more difficult that it might first appear.

It 22 is made difficult by the fact that there 21 are several ways get text and there is inconsistent 20 support by applications and controls. There 19 are two patterns that are of some use, ValuePattern and 18 TextPattern. By convention the Name property contains 17 text displayed to the user however adherence 16 to this is inconsistent. Below is a helper 15 method that I've used in UI automation for 14 testing. It basically goes through those 13 patterns checking the control for support 12 and falls back to the Name.

public static class AutomationExtensions
{
    public static string GetText(this AutomationElement element)
    {
        object patternObj;
        if (element.TryGetCurrentPattern(ValuePattern.Pattern, out patternObj))
        {
            var valuePattern = (ValuePattern)patternObj;
            return valuePattern.Current.Value;
        }
        else if (element.TryGetCurrentPattern(TextPattern.Pattern, out patternObj))
        {
            var textPattern = (TextPattern)patternObj;
            return textPattern.DocumentRange.GetText(-1).TrimEnd('\r'); // often there is an extra '\r' hanging off the end.
        }
        else
        {
            return element.Current.Name;
        }
    }
}

This takes care 11 of getting the text out of simple controls 10 like labels, textboxes (both vanilla textbox 9 and richtextbox), and buttons. Controls 8 like listboxes and comboboxes (esp. in WPF) can 7 be tricker because their items can be virtualized 6 so they may not exist in the automation 5 tree until the user interacts with them. You 4 may want to filter and call this method 3 only on certain UI Automation control types 2 like Edit, Text, and Document which you 1 know contain text.

Score: 2

Mike Zboray answer works fine. In case you 2 have access to pattern-Matching, here is 1 the same (condensed) code :

public static class AutomationExtensions
{
    public static string GetText(this AutomationElement element)
    => element.TryGetCurrentPattern(ValuePattern.Pattern, out object patternValue) ? ((ValuePattern)patternValue).Current.Value
        : element.TryGetCurrentPattern(TextPattern.Pattern, out object patternText) ? ((TextPattern)patternText).DocumentRange.GetText(-1).TrimEnd('\r') // often there is an extra '\r' hanging off the end.
        : element.Current.Name;
}

More Related questions