-1

I have such piece of code:

    private void button1_Click(object sender, EventArgs e) {
        // Do something...
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyData == Keys.A) {
            // Call button1_Click.
        }
    }

How do I manage to call the Click event? What should I write instead of

            // Call button1_Click.

Thank you!

nhtrnm
  • 1,411
  • 3
  • 15
  • 24
  • 1
    Use methods instead of faking events. Events should not be called but are triggered. So extract the relevant code in `button1_Click` and add it to a new method with a meaningful name. Then call this method from `button1_Click` and from `Form1_KeyDown`. – Tim Schmelter Sep 19 '13 at 21:31
  • You should never put functional code into an event. Make a method of what you want to reuse and call it from both places. – crthompson Sep 19 '13 at 21:33
  • button1_Click(sender, null) will probably work if you don't use 'e' – Rob Sep 19 '13 at 21:33
  • Do you want to mimic the mouse click? – Alireza Sep 19 '13 at 21:33

2 Answers2

2

Events are meant to be triggered not called. So you can trigger the event in your Form1_KeyDown event by performing the button click. I mean

    private void Form1_KeyDown(object sender, KeyEventArgs e) {
            if (e.KeyData == Keys.A) {
                button1.PerformClick();
            }
    }
0

Since the button click event handler is just a method, you could just do:

private void Form1_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyData == Keys.A) {
        button1_Click(this, e);
    }
}

However, it's often a better idea to move the logic into a separate method, and call it from both locations. By refactoring the logic within button1_Click into it's own method, you make it clear that you're calling that logic from either set of event handlers.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373