Alex Gordon
Alex Gordon

Reputation: 60902

c# is it possible to trigger the button_click event with code?

i dont want to click the button. instead, i just want to run the click event code. how would i do this?

Upvotes: 6

Views: 973

Answers (5)

rsenna
rsenna

Reputation: 11992

Option: use PerformClick().

Take a look here: How to: Call a Button's Click Event Programmatically.

The advantage here is that the event behavior will be exactly the same as a real button click (as oposed of calling button1_click directly).

But none of this options is the best IMHO. If you need to call the event handler code, you need a new method! Just refactor the old button1_click into a new, standard method and call it from wherever you want.

Upvotes: 9

Ben Voigt
Ben Voigt

Reputation: 283941

From inside or outside the Form where the Button is? Simplest thing is to just call the function:

Button1_Click(Button1, EventArgs.Empty);

Upvotes: 2

BeemerGuy
BeemerGuy

Reputation: 8279

I sometimes do that by actually calling the event handler function, that's if I actually implemented it.
Literally call it like:

button1_Click(this, new EventArgs());

Upvotes: 1

cichy
cichy

Reputation: 10644

button1_click(null, new EventArgs() );

Upvotes: 12

LostInTheCode
LostInTheCode

Reputation: 1744

Try a keybd_event with p/invoke http://msdn2.microsoft.com/en-us/library/ms646304(VS.85).aspx

Upvotes: 1

Related Questions