我正在尝试提取给定窗口中的所有文本。 我为此使用UIAutomationClient,但我愿意考虑其他方法。
我的代码在某些窗口(MS Word,Visual Studio)上运行良好,但在其他窗口(Edge,Chrome)上则运行失败。 问题在于UIAutomation框架无法检测到具有TextPattern模式的控件。
示例代码如下:
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}");
}
}
}
}
}
}