windows - 从窗口中提取所有文本
问题描述
我正在尝试提取给定窗口中的所有文本。我为此使用 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}");
}
}
}
}
}
}
解决方案
推荐阅读
- sas - 如何使规范的 PROC CALIS LINEQS 示例工作?
- html - 提供使用 HTML 将项目添加到日历的选项 - 仅限 Outlook
- javascript - 计算 2 个数组中的每个值,如果每个数组的长度不同,则推送具有较长长度的值
- r - 根据时间查找两个目录(在十分钟的 bin 中)。恶魔般的目录灾难
- vb.net - 如何限制 GetFiles 以获取在某个日期之后创建的所有路径?
- html - 为什么 Firefox 忽略 css :hover 选择器?
- apache-kafka - 无法消费来自 ClickHouse 中主题分区的消息
- javascript - 如何在restify应用程序中使用passportjs中间件
- bash - 在 SLURM 之外使用 srun
- c - 区分文件系统上的文件