How do I get access to a MessageBox through WPF Automation API?
See the question and my original answer on StackOverflowLets suppose you have that simple WPF application:
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>
Code:
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();
}