How to programmatically click a button in WPF

2011-10-07


Actually, there is no big different if you want to programmatically click a button in either WPF or Windows Form. They might have slightly different approach.

Click:

Button1.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

Press:

typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Button1, new object[] );

Unpress:

typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Button1, new object[] );

Other solution is just ButtonAutomationPeer:

Please check this blog;