c# - 使用 Microsoft UI Automation 获取任何应用程序的 TitleBar Caption?

标签 c# .net vb.net ui-automation microsoft-ui-automation

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 的那个)来分析目标应用程序。 因此,例如,当我运行记事本时,我运行检查并看到这个:

enter image description here

我看到标题栏是主窗口的直接子项,所以我可以查询直接子项的窗口树并使用 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/

相关文章:

c# - jQuery Accordion 阻止路由链接在 ListView 中工作

vb.net - 将VB6应用程序移植到VB.Net:谁能做到这一点?

asp.net - asp.net 中的土耳其字符

c# - 如何使用 Mailkit/MimeKit IMAP 将所有邮件保存到单个 .mbox 文件?

c# - 使用 AccountManagement *快速*将多个用户添加到 AD 组

c# - 动态正则表达式生成,用于数据馈送中可预测的重复字符串模式

c# - 不正确的值被放入 C# 中的列表中

c# - 为只读属性赋值适用于固定值,但不适用于变量

c# - 在内存中将 BMP 转换为 PNG,以便在 .Net 中粘贴剪贴板

c# - 如何在 C# 的 CheckedListBox 中对项目进行分组并向每个组添加标签