【发布时间】:2020-01-30 18:07:48
【问题描述】:
我想在另一个 WinForms 应用程序显示的 MessageBox 上捕获 OK 按钮的 Click 事件。
我想使用 UI 自动化来实现这一点。经过一番研究,我发现 IUIAutomation::AddAutomationEventHandler 将为我完成这项工作。
虽然我可以捕获任何其他按钮的Click 事件,但我无法捕获MessageBox 的Click 事件。
我的代码如下:
var FindDialogButton = appElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "OK"));
if (FindDialogButton != null)
{
if (FindDialogButton.GetSupportedPatterns().Any(p => p.Equals(InvokePattern.Pattern)))
{
Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, FindDialogButton, TreeScope.Element, new AutomationEventHandler(DialogHandler));
}
}
private void DialogHandler(object sender, AutomationEventArgs e)
{
MessageBox.Show("Dialog Button clicked at : " + DateTime.Now);
}
编辑:
我的完整代码如下:
private void DialogButtonHandle()
{
AutomationElement rootElement = AutomationElement.RootElement;
if (rootElement != null)
{
System.Windows.Automation.Condition condition = new PropertyCondition
(AutomationElement.NameProperty, "Windows Application"); //This part gets the handle of the Windows application that has the MessageBox
AutomationElement appElement = rootElement.FindFirst(TreeScope.Children, condition);
var FindDialogButton = appElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "OK")); // This part gets the handle of the button inside the messagebox
if (FindDialogButton != null)
{
if (FindDialogButton.GetSupportedPatterns().Any(p => p.Equals(InvokePattern.Pattern)))
{
Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, FindDialogButton, TreeScope.Element, new AutomationEventHandler(DialogHandler)); //Here I am trying to catch the click of "OK" button inside the MessageBox
}
}
}
}
private void DialogHandler(object sender, AutomationEventArgs e)
{
//On Button click I am trying to display a message that the button has been clicked
MessageBox.Show("MessageBox Button Clicked");
}
【问题讨论】:
-
什么是
appElement?在将处理程序添加到其元素之一之前,您需要识别消息框(如果消息框实际上是MessageBox)。在此处查看使用 UI 自动化的答案:How to get the text of a MessageBox when it has an icon? 以使其正常工作。 -
appElement 是 MessageBox 在其中打开的另一个应用程序。而且我已经在 FindDialogButton 中识别了 MessageBox。在里面我得到了 MessageBox 的句柄。
-
appElement 是 MessageBox 在其中打开的另一个应用程序。 UI 自动化不处理 Application 元素,它处理控件。所以,
appElement应该是一个Window元素。MessageBox不属于另一个窗口,它是一个独立的窗口。你是如何检测到这个 MessageBox 的打开的?缺少这部分代码,因此我不知道您现在正在处理什么。 -
是的,这就是我的意思,appElement 是一个窗口。我正在通过这一行检测 MessageBox 的打开 var FindDialogButton = appElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "OK"));我也可以通过ClassName找到消息框不是问题,这里的问题是我想检测对话框按钮的点击
-
这不是检测
WindowOpened事件的方法。 MessageBox 不是另一个 Window 的后代。请参阅我第一条评论中的链接。
标签: c# .net winforms button ui-automation