我想要捕获由另一个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(如果MessageBox实际上是MessageBox)的身份。请参见此处使用UI自动化的答案:当MessageBox有图标时如何获取其文本?,以使其正常工作。 - JimiappElement
)的后代(TreeScope.Descendants
)。var FindDialogButton = appElement.FindFirst(...)
将什么也找不到。请参阅我第一条评论中的链接。您需要使用 WindowOpenedEvent。 - Jimi