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}");
}
}
}
}
}
}