简体   繁体   中英

Visual Studio C# Capturing Enter Key In Textbox

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM