6

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

2
  • 1
    The short answer is Yes! Commented Nov 8, 2010 at 22:11
  • 1
    If you have control of the code in the click event handler, the correct thing to do is to extract that code to a separate method that can be called from anywhere. Commented Nov 8, 2010 at 22:24

5 Answers 5

12
button1_click(null, new EventArgs() );
Sign up to request clarification or add additional context in comments.

2 Comments

And pray that the sender argument isn't used.
if you would like use sender than you simply put it instead of null.
9

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.

2 Comments

+1: I've always assumed PerformClick is better than calling the button's handler directly, as the framework knows better than you do as to anything special it needs to do. It also addresses Ben Voigt's comment about the sender argument.
+1 for refactor of the old button1_click, makes so much sense
2

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

Button1_Click(Button1, EventArgs.Empty);

Comments

1

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

Comments

1

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.