2015-06-16 72 views
2

C#否则VB.Net,我怎么会用微软UI自动化检索包含文本的控件的文本?使用Microsoft UI Automation获取任何应用程序的标题栏标题?

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

Obtain Text Attributes Using UI Automation

然后,例如,用下面的代码,我试着给那个窗口的HWND检索窗口标题栏的文本,但我不知道exactlly如何遵循标题栏找到真正包含文本的子控件(标签?)。

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。

+0

你知道这是一个WPF的东西,对吗? – Plutonix

+0

它也适用于WinForms以及任何C/C++ bin,使用UI自动化您可以监视/检查所有类型的可执行文件,不仅WPF,但我知道MSDN信息非常令人困惑。 – ElektroStudios

+0

我只是想确定你知道它是什么。 – Plutonix

回答

3

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

enter image description here

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

这是一个示例控制台应用程序C#代码,演示了如何获得'无标题 - 记事本'标题。请注意,标题栏也支持值模式,但我们不需要这里,因为标题栏的名称也是值。

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

如果您想获得所有窗口标题,该怎么办?例如:Notepad ++窗口标题...? – Codexer

+0

这是另一个问题。每个应用程序都与UI自动化有所不同。偶然的答案也可以从同一个人在这里:http://stackoverflow.com/questions/29951432/is-it-possible-to-activate-a-tab-in-another-program-using-an-intptr –

+0

不错,谢谢参考! – Codexer

相关问题