Search code examples
c#.netwpfbutton

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?


Solution

  • 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;
    invokeProv.Invoke();
    

    Here is a blog post on the subject.

    Note: IInvokeProvider interface is defined in the UIAutomationProvider assembly.