Get TitleBar Caption of any application using Microsoft UI Automation?

前端 未结 1 1177
萌比男神i
萌比男神i 2021-01-06 10:49

In C# or else VB.Net, how I could use Microsoft UI Automation to retrieve the text of any control that contains text?.

1条回答
  •  鱼传尺愫
    2021-01-06 11:29

    With UI Automation, in general, you have to analyze the target application using the SDK tools (UISpy or Inspect - make sure it's Inspect 7.2.0.0, the one with a tree view). So here for example, when I run notepad, I run inspect and see this:

    enter image description here

    I see the titlebar is a direct child of the main window, so I can just query the window tree for direct children and use the TitleBar control type as a discriminant because there's no other child of that type beneath the main window.

    Here is a sample console app C# code that demonstrate how to get that 'Untitled - Notepad' title. Note the TitleBar also supports the Value pattern but we don't need here because the titlebar's name is also the value.

    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);
        }
    }
    

    0 讨论(0)
提交回复
热议问题