如何通过 WPF 自动化 API 访问 MessageBox? [英] How do I get access to a MessageBox through WPF Automation API?

查看:17
本文介绍了如何通过 WPF 自动化 API 访问 MessageBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用低级 WPF 自动化 API 访问 MessageBox?

How do I get access to MessageBox using the low level WPF Automation API?

我已经搜索了所有内容,但关于此的文档似乎很少.我宁愿不使用白色,因为我需要更多的控制权.

I have searched all over but there seems to be very little documentation for this. I would rather not use White as I need more control than it gives.

谢谢

推荐答案

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

Lets suppose you have that simple WPF application:

XML:

<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");
    }
}

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

You can automate this application with a console app sample like this (run this once you have started the first project):

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 自动化 API 访问 MessageBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆