Как мне получить доступ к MessageBox через WPF Automation API?

#wpf #ui-automation

#wpf #пользовательский интерфейс-автоматизация

Вопрос:

Как мне получить доступ к MessageBox с помощью низкоуровневого WPF Automation API?

Я искал повсюду, но, похоже, для этого очень мало документации. Я бы предпочел не использовать White, поскольку мне нужно больше контроля, чем он дает.

Спасибо

Комментарии:

1. Что вы подразумеваете под «получением доступа» к MessageBox? Что именно вы хотите сделать?

2. Мне нужен доступ к его структуре, чтобы проверить ее (например, проверить текст / заголовок на соответствие ожидаемым значениям) и нажать на нее кнопки.

Ответ №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();
    }