如何订阅在System.Windows.Automation中打开的弹出窗口

本文关键字:窗口 何订阅 System Windows Automation | 更新日期: 2023-09-27 18:32:34

我正在尝试使用System.Windows.Automation库进行一些 UI 测试,并且能够取得一些进展,但我无法订阅在我的应用程序中创建弹出窗口的事件。我尝试在根(桌面对象)和窗口上使用Automation.AddStructureChangedEventHandler,但这不起作用。我还尝试使用不同的范围,但也没有帮助。

AutomationElement desktop = AutomationElement.RootElement;
AutomationElement app = desktop
    .FindFirst(TreeScope.Children,
        new PropertyCondition(AutomationElement.NameProperty,
            "Name of the App", PropertyConditionFlags.IgnoreCase));
ActivateWindow(app);
AutomationElement appWindow = app
    .FindFirst(TreeScope.Children,
        new PropertyCondition(AutomationElement.ControlTypeProperty,
            ControlType.Window));
// Find a button that opens a popup window and click it
AutomationElement button = appWindow
    .FindFirst(TreeScope.Children, Condition.TrueCondition)
    .FindAll(TreeScope.Children, Condition.TrueCondition)[8];
MoveMouseToAndClick(button);
Automation.AddStructureChangedEventHandler(desktop, TreeScope.Descendants, setupWindowOpen);

setupWindowOpen处理程序有时会触发,但看起来这种情况发生在其他应用程序上,而不是我的应用程序(我在发送方元素对象上看到了 Internet Explorer ID)。提前谢谢。

如何订阅在System.Windows.Automation中打开的弹出窗口

弹出控件很棘手,因为它们可以直接位于桌面下方或应用程序下方,或者可能位于其他任何地方(桌面的直接子级是最好的猜测)。我建议您使用 Microsoft SDK 附带的 WinSDK_AccEvent.exe 实用程序来测试弹出窗口的行为,其中包含各种事件,例如:桌面和自动化应用程序上的 WindowOpened、StructureChanged、ToolTipTOpen。这应该为您提供要订阅的正确事件以及订阅范围。重要提示:如果使用的是UI 自动化框架的托管版本,则最好迁移到本机版本,因为托管版本对可以捕获的内容有限制,并且存在一些无法克服的性能 bug。此外,它显然不再得到官方支持。希望这有帮助。

您可以订阅WindowOpenedEvent(请参阅此页面)。这看起来很容易,但我在让它工作时遇到了问题。

如果您仍然对UI测试感兴趣并且熟悉Selenium驱动程序,则可以尝试我在 https://github.com/kfrajtak/WinAppDriver 提供的实现。