如何通过WPF Automation API访问MessageBox?

时间:2014-06-29 21:49:43

标签: wpf ui-automation

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

我已经搜遍过,但似乎很少有文档。我宁愿不使用怀特,因为我需要更多的控制而不是它。

由于

1 个答案:

答案 0 :(得分:1)

让我们假设你有这个简单的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();
    }