首页 > 解决方案 > 从窗口中提取所有文本

问题描述

我正在尝试提取给定窗口中的所有文本。我为此使用 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}");
                    }
                }
            }
        }
    }
}

标签: windowsautomationaccessibilityui-automation

解决方案


推荐阅读