How to programmatically click a button in WPF

Published on Friday, October 7, 2011
c wpf

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;