0

Scenario is:

  • I have a button called X in project A
  • One of the events for X is the following:

    private void X_KeyDown(object sender, KeyEventArgs e)
    {//if the user presses Ctrl + V 
        if (e.KeyCode == Keys.Control && e.KeyCode == Keys.V)
        {
          MessageBox.Show("hello");  
        }
    }
    
  • I've now created a new poject B and added a button to a form and also called it X. I then copied the above code into Form1.cs.

Question: If I go to form B and select the button and then double click the KeyDown event it does not go to the code I copied in but creates the following. Why ?

private void X_KeyDown_1(object sender, KeyEventArgs e)
{

}
Rob
  • 4,927
  • 12
  • 49
  • 54
whytheq
  • 34,466
  • 65
  • 172
  • 267

1 Answers1

1

Because you have neglected to copy the actual event binding, which is declared in your Form1.Designer.cs file. Something like

X.Click += new System.KeyDownEventHandlerEtcEtc;

Because this is missing, the studio thinks you're trying to create a new event handler. But because the default name for that event handler it tacks on a _1.

To overcome this, you can set the Click event in the designer manually to the specified, copied event handler. Or indeed any event handler with a matching signature.

Another way to do this is to not copy the entire event handler, but only the logic - then create a new handler in your new Form, pasting the logic there.

J. Steen
  • 15,470
  • 15
  • 56
  • 63