5

I am trying to capture the Enter key in a Windows Forms Textbox. I got this fragment of code from a tutorial:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    //
    // Detect the KeyEventArg's key enumerated constant.
    //
    if (e.KeyCode == Keys.Enter)
    {
        MessageBox.Show("You pressed enter! Good job!");
    }
    else if (e.KeyCode == Keys.Escape)
    {
        MessageBox.Show("You pressed escape! What's wrong?");
    }
}

but now my code throws a compile/build error:

The event 'System.Windows.Forms.Control.Enter' can only appear on the left hand
side of += or -=    Line 44 Column 84

On the one hand I don't understand the error message. On the other hand line 44 is a blank line having only a newline character.

Any advice is appreciated.

Regards.

4
  • 2
    The problem is in the .designer.cs file. Try unsubscribing and resubscribing to the event. Jun 1, 2012 at 16:41
  • Code shown here looks ok. How do you subscribe to your event and what's on lines 43,44 and 45?
    – walther
    Jun 1, 2012 at 16:42
  • Better yet: Here's lines 43, 44, 45: ` } private void button1_Click(object sender, EventArgs e) ` The curly brace on line 43 is the closing brace to the code above. I'm not sure if I am subscribing to this event or not I just copied the code off of a tutorial. This doesn't show up very well. Line 43 is the curly brace. Line 44 is blank. Line 45 is the method prototype.
    – Kevin
    Jun 1, 2012 at 17:44
  • Ignore my previous comments. I was looking in the wrong file. :-(
    – Kevin
    Jun 1, 2012 at 18:08

1 Answer 1

2

Check the Designer file (form.Designer.cs)

Your Designer should be:

this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);

You may have subscribed to the Enter event. That is actually not the Enter key. That is for being on it, and it is paired with the Leave event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.