使用 Microsoft UI 自动化获取任何应用程序的 TitleBar 标题?

Ele*_*ios 4 .net c# vb.net ui-automation microsoft-ui-automation

C#VB.Net 中,我如何使用Microsoft UI 自动化来检索包含文本的任何控件的文本?。

我一直在 MSDN 文档中进行研究,但我不明白。

使用 UI 自动化获取文本属性

然后,例如,使用下面的代码,我试图通过提供该窗口的 hwnd 来检索窗口标题栏的文本,但我不知道如何按照标题栏找到子控件(标签?)这确实包含文本。

Imports System.Windows.Automation
Imports System.Windows.Automation.Text
Run Code Online (Sandbox Code Playgroud)

.

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)
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我正在尝试使用标题栏,但只是我想使用任何其他包含文本的控件来执行此操作……例如标题栏。

PS:我知道 P/Invoking GetWindowTextAPI。

Sim*_*ier 5

对于 UI 自动化,通常,您必须使用 SDK 工具(UISpy 或 Inspect - 确保它是 Inspect 7.2.0.0,具有树视图的工具)分析目标应用程序。因此,例如,当我运行记事本时,我运行检查并看到:

在此处输入图片说明

我看到标题栏是主窗口的直接子窗口,因此我可以查询直接子窗口的窗口树,并使用 TitleBar 控件类型作为判别式,因为主窗口下方没有该类型的其他子窗口。

这是一个示例控制台应用程序 C# 代码,演示了如何获取“无标题 - 记事本”标题。注意 TitleBar 也支持 Value 模式,但我们在这里不需要,因为 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);
    }
}
Run Code Online (Sandbox Code Playgroud)