在 C# 或 VB.Net 中,如何使用 Microsoft UI Automation 检索任何包含文本的控件的文本? .
我一直在研究 MSDN 文档,但我不明白。
Obtain Text Attributes Using UI Automation
然后,例如,使用下面的代码,我试图通过提供该窗口的 hwnd 来检索窗口标题栏的文本,但我不知道如何按照标题栏查找子控件(标签?)真正包含文本。
Imports System.Windows.Automation
Imports System.Windows.Automation.Text
.
Dim hwnd As IntPtr = Process.GetProcessesByName("notepad").First.MainWindowHandle
Dim targetApp As AutomationElement = AutomationElement.FromHandle(hwnd)
' The control type we're looking for; in this case 'TitleBar'
Dim cond1 As New PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TitleBar)
Dim targetTextElement As AutomationElement =
targetApp.FindFirst(TreeScope.Descendants, cond1)
Debug.WriteLine(targetTextElement Is Nothing)
在上面的示例中,我正在尝试使用标题栏,但我只想使用包含文本的任何其他控件...例如标题栏。
PS:我知道 P/Invoking GetWindowText
API。
最佳答案
对于 UI Automation,通常,您必须使用 SDK 工具(UISpy 或 Inspect - 确保它是 Inspect 7.2.0.0,具有 TreeView 的那个)来分析目标应用程序。 因此,例如,当我运行记事本时,我运行检查并看到这个:
我看到标题栏是主窗口的直接子项,所以我可以查询直接子项的窗口树并使用 TitleBar 控件类型作为判别,因为主窗口下方没有该类型的其他子项。
这是一个示例控制台应用程序 C# 代码,演示了如何获取“无标题 - 记事本”标题。请注意,TitleBar 也支持值模式,但我们在这里不需要,因为标题栏的名称也是值。
class Program
{
static void Main(string[] args)
{
// start our own notepad from scratch
Process process = Process.Start("notepad.exe");
// wait for main window to appear
while(process.MainWindowHandle == IntPtr.Zero)
{
Thread.Sleep(100);
process.Refresh();
}
var window = AutomationElement.FromHandle(process.MainWindowHandle);
Console.WriteLine("window: " + window.Current.Name);
// note: carefully choose the tree scope for perf reasons
// try to avoid SubTree although it seems easier...
var titleBar = window.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TitleBar));
Console.WriteLine("titleBar: " + titleBar.Current.Name);
}
}
关于c# - 使用 Microsoft UI Automation 获取任何应用程序的 TitleBar Caption?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30875408/