Windows 从窗口中提取所有文本
我正在尝试提取给定窗口中的所有文本。 我正在使用UiAutoCuto客户端,但我愿意考虑其他方式。 我的代码在某些windows(MS Word、Visual Studio)上运行良好,但在其他windows(Edge、Chrome)上运行失败。 问题是UIAutomation框架没有检测到具有TextPattern模式的控件 示例代码如下:Windows 从窗口中提取所有文本,windows,automation,accessibility,ui-automation,Windows,Automation,Accessibility,Ui Automation,我正在尝试提取给定窗口中的所有文本。 我正在使用UiAutoCuto客户端,但我愿意考虑其他方式。 我的代码在某些windows(MS Word、Visual Studio)上运行良好,但在其他windows(Edge、Chrome)上运行失败。 问题是UIAutomation框架没有检测到具有TextPattern模式的控件 示例代码如下: using System; using System.Diagnostics; using System.Text.RegularExpressions;
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}");
}
}
}
}
}
}
使用系统;
使用系统诊断;
使用System.Text.RegularExpressions;
使用System.Windows.Automation;
命名空间转储文本
{
班级计划
{
静态void Main(字符串[]参数)
{
//var procs=Process.getProcessByName(“winword”);//有效!
//var procs=Process.getProcessByName(“devenv”);//有效!
var procs=Process.getProcessByName(“MicrosoftEdge”);//找不到文本
//var procs=Process.getProcessByName(“chrome”);//找不到文本
正则表达式rex=新正则表达式(\\s+);
foreach(var proc in procs)
{
如果(proc.MainWindowHandle.ToInt64()==0){continue;}
var targetWindow=(AutomationElement.FromHandle(proc.MainWindowHandle));
WriteLine($“窗口标题:{proc.MainWindowTitle}”);
var textPatternAvailable=新属性条件(AutomationElement.IsTextPatternAvailableProperty,true);
AutomationElementCollection集合=targetWindow.FindAll(TreeScope.substands,textPatternAvailable);
for(int i=0;i
您可以使用inspect工具查看它是否能够读取文本。这一点很好。我运行Inspect并点击了一些文本。在Edge上运行良好,我可以看到文本,并且IsTextPatternAvailable是真实的。没有在Chrome上工作,可用的IsTextPatternAvailable为false。因此,至少对于Edge,我显然没有正确地遍历文本元素。