19 August 2011

How to programmatically click a button - WPF

Back in WinForms it was really easy to simulate a user clicking a Button, you just call a Button’s PerformClick method. In WPF it's not quite as intuitive as the old Windows Forms way, but it is more powerful since you can raise most events now.

System.Windows.Controls.Button btnLaunch = new Button();

btnLaunch.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, btnLaunch));

Since I love the new 3.5 Extensions, I've made an extension method that mimics the old Windows Forms method.

/// <summary>

/// Manally performs a <seealso cref="System.Windows.Controls.Button.Click"/> event for a supplied

/// <seealso cref="System.Windows.Controls.Button"/>.

/// </summary>

/// <param name="btnObject">The <seealso cref="System.Windows.Controls.Button"/> object to

/// be clicked.</param>

public static void PerformClick(this System.Windows.Controls.Button btnObject)



new System.Windows.RoutedEventArgs(




Search This Blog

Total Pageviews