wpf - 如何通过 WPF Automation API 访问 MessageBox?

标签 wpf ui-automation

如何使用低级 WPF Automation API 访问 MessageBox?

我已经到处搜索了,但似乎这方面的文档很少。我宁愿不使用白色,因为我需要比它提供的更多控制。

谢谢

最佳答案

假设您有一个简单的 WPF 应用程序:

Xaml:

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <Grid>
        <Button Name="Button1" Content="Click Me" Click="Button1_Click" />
    </Grid>
</Window>

代码:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(this, "hello");
    }
}

您可以使用如下所示的控制台应用程序示例自动化此应用程序(在启动第一个项目后运行此示例):

class Program
{
    static void Main(string[] args)
    {
        // get the WPF app's process (must be named "WpfApplication1")
        Process process = Process.GetProcessesByName("WpfApplication1")[0];

        // get main window
        AutomationElement mainWindow = AutomationElement.FromHandle(process.MainWindowHandle);

        // get first button (WPF's "Button1")
        AutomationElement button = mainWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));

        // click it
        InvokePattern invoke = (InvokePattern)button.GetCurrentPattern(InvokePattern.Pattern);
        invoke.Invoke();

        // get the first dialog (in this case the message box that has been opened by the previous button invoke)
        AutomationElement dlg = mainWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "Dialog"));
        AutomationElement dlgText = dlg.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text));

        Console.WriteLine("Message Box text:" + dlgText.Current.Name);

        // get the dialog's first button (in this case, 'OK')
        AutomationElement dlgButton = dlg.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));

        // click it
        invoke = (InvokePattern)dlgButton.GetCurrentPattern(InvokePattern.Pattern);
        invoke.Invoke();
    }

关于wpf - 如何通过 WPF Automation API 访问 MessageBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24480596/

相关文章:

wpf - 如何在自定义控件中绑定(bind)

wpf - WPF 设计器中的字段选择 - 没有下拉菜单?

android - onView(allOf(withId(R.id.login_card_view), isDisplayed())) 和 check(matches(isDisplayed())) 之间的区别

javascript - 日期选择器上的 selectValue 不起作用

java - 如何在 selenium webdriver 中将值从一个测试用例传递到另一个测试用例

c# - Atata 框架上的 Link 和 DelegateLink 有什么区别?

c# - 将缓存与 AutomationElements 一起使用不会给我加速 - 预期或错误的用法?

c# - 阿瓦隆码头 : how to align the tabs to the top right?

wpf - 使用 WPF Prism/Mahapps HamburgerMenu 控件时调用参数化 View 模型构造函数

wpf - 为什么我的 WPF 文本框 "kinda"是只读的?