How to programmatically click a button in WPF?


Since there's no button.PerformClick() method in WPF, is there a way to click a WPF button programmatically?

5/6/2019 4:33:24 AM

Accepted Answer

WPF takes a slightly different approach than WinForms here. Instead of having the automation of a object built into the API, they have a separate class for each object that is responsible for automating it. In this case you need the ButtonAutomationPeer to accomplish this task.

ButtonAutomationPeer peer = new ButtonAutomationPeer(someButton);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;

Here is a blog post on the subject.

Note: IInvokeProvider interface is defined in the UIAutomationProvider assembly.

12/1/2017 8:29:09 AM

Like JaredPar said you can refer to Josh Smith's article towards Automation. However if you look through comments to his article you will find more elegant way of raising events against WPF controls

someButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));

I personally prefer the one above instead of automation peers.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow