Tuesday, March 15, 2011

Raise button (or any control) click event manually. C#

Can anyone tell me how to raise click event of button control (or for that matter for any event).

Platform: .net 2.0/3.0/3.5 Language: c# Domain: Windows Application, WinForms, etc.

From stackoverflow
  • You can use the Button.PerformClick method.

    Adam Robinson : +1. As for any other events, the Event structure is specifically designed to make the owner of the event the only object capable of directly invoking it. The Button class exposes PerformClick to allow you to simulate a click, but not all events will have this (for good reason).
    Asad Malik : thanks buddy... so simple and yet.... :D you are a life saver... :D
  • You can also look into Windows Accessibility or some UI automation framework that allows you to programmatically cause UI controls to respond to user gestures. If a control does not offer a way for its events to be programmatically triggered like PerformClick, you can derive from that control and expose a public method like PerformnXXX that when called internally invokes the event handlers subscribed to a particular event.

  • Maybe the solution is much more simple:

    Maybe you don't really want your code "to click the button".
    Do you just want to run the code which is behind the button from another place in the form?

    If yes, put the code into a separate method (like "DoActionXXX") and call the method from the button and from everywhere else where you need it.

0 comments:

Post a Comment