How to programmatically click a button

Back in WinForms it was really easy to simulate a user clicking a Button, you just call a Button’s PerformClick method. For some reason the WPF Button does not have that method. It turns out that you need to enter into the automation world to accomplish this task.

Share this:

Like this:

LikeLoading...

Related

This entry was posted on Friday, March 9th, 2007 at 8:59 am and is filed under Praxis. You can follow any responses to this entry through the RSS 2.0 feed.
Both comments and pings are currently closed.

Post navigation

15 Responses to How to programmatically click a button

You may want to get the AutomationPeer from the element instead of assuming the type of automation peer to create – i.e. use UIElementAutomationPeer.CreatePeerForElement. Note, despite the name, it will only create it if the element doesn’t already have one created – otherwise it uses the one previously created for the element.

The benefit of this is that you have a reusable command divorced from the Button UIElement and can do stuff like handle the command’s CanExecute event to enable and disable the command based upon some condition.

Actually I think Neil’s point is more that if you had a Command associated with the Button that using RaiseEvent would not cause that command to be executed since the command associated with the button is only executed from the OnClick of the ButtonBase after it has raised the Click event. I think that’s a stronger argument for using the automation method.

Additionally, the RaiseEvent results in a call to the event handler while still in the calling method. The automation peer method causes the event to be triggered after the invoking method has ended. Just put a breakpoint at the start of the click handler and inspect the call stack to see this. Depending on your circumstances, the automation method may be preferable.

Josh, suppose I wanted to spoof a mouse click (or more specifically a mouse down) over a TextBox; how might I go about doing that? I’ve explored both RaiseEvent and UI Automation (the latter just left me baffled), but neither offer an obvious way to do this.

The reason I need to do this is that I want mouse clicks over a text box to by default go towards dragging a window, and only if the mouse is clicked and released (without moving) should it be passed-on to the TextBox. The problem is that by the time I can determine if it has moved (mouseUp), the initial mouseDown is lost. Is there some way I can recreate it in such a way that it can be sent again, this time with IsHitTestVisible set to true on the text box?

I already know how to use SendInput, but I was hoping there was a managed solution via WPF.