Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger control's event programmatically

Assume that I have a WinFoms project. There is just one button (e.g. button1).

The question is: is it possible to trigger the ButtonClicked event via code without really clicking it?

like image 633
steavy Avatar asked Aug 29 '12 18:08

steavy


3 Answers

Button controls have a PerformClick() method that you can call.

button1.PerformClick();
like image 161
itsme86 Avatar answered Oct 24 '22 21:10

itsme86


The .NET framework uses a pattern where for every event X there is a method protected void OnX(EventArgs e) {} that raises event X. See this Msdn article. To raise an event from outside the declaring class you will have to derive the class and add a public wrapper method. In the case of Button it would look like this:

class MyButton : System.Windows.Forms.Button
{

    public void ProgrammaticClick(EventArgs e)
    {
        base.OnClick(e);
    }

}
like image 25
TomBot Avatar answered Oct 24 '22 22:10

TomBot


You can just call the event handler function directly and specify null for the sender and EventArgs.Empty for the arguments.

void ButtonClicked(object sender, EventArgs e)
{
    // do stuff
}

// Somewhere else in your code:
button1.Click += new EventHandler(ButtonClicked);

// call the event handler directly:
ButtonClicked(button1, EventArgs.Empty);

Or, rather, you'd move the logic out of the ButtonClicked event into its own function, and then your event handler and the other code you have would in turn call the new function.

void StuffThatHappensOnButtonClick()
{
    // do stuff
}

void ButtonClicked(object sender, EventArgs e)
{
    StuffThatHappensOnButtonClick();
}

// Somewhere else in your code:
button1.Click += new EventHandler(ButtonClicked);

// Simulate the button click:
StuffThatHappensOnButtonClick();

The latter method has the advantage of letting you separate your business and UI logic. You really should never have any business logic in your control event handlers.

like image 17
Cᴏʀʏ Avatar answered Oct 24 '22 21:10

Cᴏʀʏ