C# 使用Microsoft UI Automation获取任何应用程序的标题栏标题?
在C#或其他VB.Net中,我如何使用Microsoft UI Automation检索包含文本的任何控件的文本 我一直在研究MSDN文档,但我不明白 然后,例如,使用下面的代码,我试图通过给出窗口的hwnd来检索窗口标题栏的文本,但我不知道如何准确地按照标题栏找到真正包含文本的子控件(标签?)C# 使用Microsoft UI Automation获取任何应用程序的标题栏标题?,c#,.net,vb.net,ui-automation,microsoft-ui-automation,C#,.net,Vb.net,Ui Automation,Microsoft Ui Automation,在C#或其他VB.Net中,我如何使用Microsoft UI Automation检索包含文本的任何控件的文本 我一直在研究MSDN文档,但我不明白 然后,例如,使用下面的代码,我试图通过给出窗口的hwnd来检索窗口标题栏的文本,但我不知道如何准确地按照标题栏找到真正包含文本的子控件(标签?) Imports System.Windows.Automation Imports System.Windows.Automation.Text 在上面的例子中,我尝试使用标题栏,但我只想使用任何
Imports System.Windows.Automation
Imports System.Windows.Automation.Text
在上面的例子中,我尝试使用标题栏,但我只想使用任何其他包含文本的控件,比如标题栏
PS:我知道p/Invoking
GetWindowText
API。使用UI自动化,通常必须使用SDK工具分析目标应用程序(UISpy或Inspect-确保它是Inspect 7.2.0.0,带有树视图的)。
例如,在这里,当我运行记事本时,我运行inspect并看到:
我看到标题栏是主窗口的一个直接子窗口,因此我可以查询窗口树中的直接子窗口,并使用标题栏控件类型作为区分符,因为主窗口下没有其他类型的子窗口
下面是一个控制台应用程序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);
}
}
你知道这是一个WPF的东西,对吗?它也适用于WinForms和任何C/C++bin,通过UI自动化,你可以监视/检查所有类型的可执行文件,不仅是WPF,而且我知道MSDN信息对此非常混乱。我只是想确定你知道它是什么。如果你想获得所有窗口标题怎么办?例如:记事本++窗口标题…?这是另一个问题。每个应用程序在UI自动化方面都是不同的。碰巧,这里的同一个人也提供了答案:@Simon Mourier谢谢你的回答,我稍后会测试它<代码>这是另一个问题。每个应用程序在UI自动化方面都是不同的,但是,例如,
GetwindowText
函数可以获取任何标题栏的文本,不管它是什么类型的应用程序,它只需要窗口hwnd并发挥神奇的作用,然后我假设使用UI自动化“引擎”我应该得到与使用WinAPI函数相同或更好的结果。不管怎样,我稍后也会阅读链接的答案。在UIA中,“它只需要窗口hwnd”这句话也是同样的问题。您只需要确定什么是窗口层次结构,不管技术是什么。使用UIA IMHO更简单,而且这是官方的方式。@SimonMourier,先生,我一直在寻找它是为了我的目的,为了我的目的,我还需要设置/更改标题栏的值。。因为我对UIAutomation不是很在行,所以我找不到实现它的方法?你能帮忙吗?
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);
}
}