在Windows中获取程序控件树信息有几种主要方案:
1. Windows UI Automation API (推荐)
这是微软官方提供的现代化解决方案,功能强大且稳定。
C# 示例:
using System;
using System.Windows.Automation;
// 获取指定进程的控件树
public void GetControlTree(int processId)
{
AutomationElement rootElement = AutomationElement.RootElement;
PropertyCondition condition = new PropertyCondition(
AutomationElement.ProcessIdProperty, processId);
AutomationElement targetApp = rootElement.FindFirst(
TreeScope.Children, condition);
if (targetApp != null)
{
WalkControlTree(targetApp, 0);
}
}
private void WalkControlTree(AutomationElement element, int depth)
{
string indent = new string(' ', depth * 2);
Console.WriteLine($"{indent}{element.Current.Name} - {element.Current.ControlType.LocalizedControlType}");
AutomationElementCollection children = element.FindAll(
TreeScope.Children, Condition.TrueCondition);
foreach (AutomationElement child in children)
{
WalkControlTree(child, depth + 1);
}
}
2. Win32 API 方案
使用传统的Windows API,轻量但功能相对有限。
C# P/Invoke 示例:
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
// 枚举子窗口
public void EnumerateControls(IntPtr parentHandle)
{
EnumChildWindows(parentHandle, EnumChildWindowsCallback, IntPtr.Zero);
}
private bool EnumChildWindowsCallback(IntPtr hWnd, IntPtr lParam)
{
StringBuilder sb = new StringBuilder(256);
GetWindowText(hWnd, sb, sb.Capacity);
Console.WriteLine($"Control: {sb.ToString()}");
return true;
}
3. 现成的工具库
FlaUI - 基于UI Automation的.NET库:
// NuGet: Install-Package FlaUI.Core
using FlaUI.Core;
using FlaUI.UIA3;
var automation = new UIA3Automation();
var app = Application.Attach(processId);
var mainWindow = app.GetMainWindow(automation);
// 遍历控件树
foreach (var element in mainWindow.FindAllDescendants())
{
Console.WriteLine($"{element.Name} - {element.ControlType}");
}
4. 实用工具
开发时可以使用这些工具来查看和分析控件树:
- Inspect.exe (Windows SDK自带)
- UISpy (较老但仍有用)
- Accessibility Insights (微软开源工具)
推荐方案
对于现代Windows应用,建议使用UI Automation API或FlaUI库,它们支持WPF、WinForms、Win32等各种应用类型,功能全面且维护良好。
你使用的是什么开发语言?我可以提供更具体的实现代码。