1

I'm trying to extract all the text in a given window. I'm using UIAutomationClient for this, but I'm willing to consider other ways.

My code works well for some windows (MS Word, Visual Studio) but fails for others (Edge, Chrome). The problem is that UIAutomation framework doesn't detect controls with a TextPattern pattern.

Sample code follows:

using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows.Automation;
namespace DumpText
{
    class Program
    {
        static void Main(string[] args)
        {
            //var procs = Process.GetProcessesByName("winword");        // Works!
            //var procs = Process.GetProcessesByName("devenv");         // Works!
            var procs = Process.GetProcessesByName("MicrosoftEdgeCp");  // Doesn't find text
            //var procs = Process.GetProcessesByName("chrome");         // Doesn't find text
            Regex rex = new Regex("\\s+");
            foreach (var proc in procs)
            {
                if (proc.MainWindowHandle.ToInt64() == 0) { continue; }
                var targetWindow = (AutomationElement.FromHandle(proc.MainWindowHandle));
                Console.WriteLine($"Window title: {proc.MainWindowTitle}");
                var textPatternAvailable = new PropertyCondition(AutomationElement.IsTextPatternAvailableProperty, true);
                AutomationElementCollection collection = targetWindow.FindAll(TreeScope.Descendants, textPatternAvailable);
                for (int i = 0; i < collection.Count; i++)
                {
                    var elem = collection[i];
                    var targetTextPattern = elem.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
                    if (targetTextPattern != null)
                    {
                        string str = targetTextPattern.DocumentRange.GetText(-1);
                        string str2 = rex.Replace(str, " ");
                        Console.WriteLine($"****{i}****\n{str2}");
                    }
                }
            }
        }
    }
}
  • You can use inspect tool to see if it can read the text. – Wander3r Jul 21 '18 at 10:43
  • Good point. I ran Inspect and clicked on some text. Works well on Edge, I could see text and the IsTextPatternAvailable was true. Didn't work on Chrome and IsTextPatternAvailable was false. So at least for Edge - I'm obviously not iterating through the text elements properly. – Aviv Hurvitz Jul 21 '18 at 11:28

0 Answers0