Windows下使用UIAutomation技术遍历桌面窗口和指定窗口内容的AutomationWalker.exe的C#源代码
·
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Automation;
//引用"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\UIAutomationClient.dll"
//引用"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\UIAutomationTypes.dll"
namespace ConsoleApp1
{
class Program
{
static void WalkElement(AutomationElement element, TreeWalker walker, int depth, int limit)
{
Console.WriteLine($"{new string(' ', depth * 2)}" + $"\"{element.Current.Name}\"");
if (limit>0 && depth>=limit) return;
AutomationElement child = walker.GetFirstChild(element);
while (child != null)
{
WalkElement(child, walker, depth + 1, limit);
child = walker.GetNextSibling(child);
}
}
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: AutomationWalker \"window_title\"|desktop");
return;
} else if (args[0]=="desktop")
{
try
{
Console.WriteLine("Walker desktop begin ...");
//Get the destkop element
AutomationElement elemDesktop = AutomationElement.RootElement;
TreeWalker walker = TreeWalker.ControlViewWalker;
WalkElement(elemDesktop, walker, 0, 1);
Console.WriteLine("... Walker desktop end.");
}
catch (Exception)
{
Console.WriteLine("Walker desktop error!");
}
return;
}
try
{
Console.WriteLine("Walker begin ...");
//Get the destkop element
AutomationElement elemDesktop = AutomationElement.RootElement;
//Search the Application main window by title from all children
PropertyCondition pCondition = new PropertyCondition(AutomationElement.NameProperty, args[0]);
AutomationElementCollection elemApplicationWindows = elemDesktop.FindAll(TreeScope.Children, pCondition);
Console.WriteLine("elemApplicationWindows.Count:" + elemApplicationWindows.Count);
for (int i = 0; i < elemApplicationWindows.Count; i++)
{
TreeWalker walker = TreeWalker.ControlViewWalker;
WalkElement(elemApplicationWindows[i], walker, 0, 0);
}
Console.WriteLine("... Walker end.");
}
catch (Exception)
{
Console.WriteLine("Walker error!");
}
}
}
}
将以上代码放在C#控制台项目中,生成AutomationWalker.exe
用法:
在cmd窗口中输入命令
AutomationWalker.exe desktop
列出当前桌面上所有窗口的用双引号括住的标题,比如
Walker desktop begin ...
""
""
"管理员: 命令提示符 - automationwalker desktop"
"新标签页 - Google Chrome"
"dummyLayeredWnd"
"Program Manager"
... Walker desktop end.
输入命令
AutomationWalker.exe "新标签页 - Google Chrome"
列出窗口"新标签页 - Google Chrome"的内容。
当你想要提取某个窗口的文本内容时,使用AutomationWalker会很方便。
更多推荐




所有评论(0)