Detect Enter Key C#

k1f1 picture k1f1 · Aug 16, 2012 · Viewed 65k times · Source

I have the following code which does not show the MessageBox when enter/return is pressed.

For any other key(i.e. letters/numbers) the MessageBox shows False.

private void cbServer_TextChanged(object sender, EventArgs e)
{
    if (enterPressed)
    {
        MessageBox.Show("Enter pressed");
    }
    else
        MessageBox.Show("False");
}

private void cbServer_Keydown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
    {
        enterPressed = true;
        MessageBox.Show("Enter presssed: " + enterPressed);

    }
    else
        enterPressed = false;
}

Any ideas?

EDIT: Above code, I thought the issue was with the _Keydown even so I only posted that.

Answer

in your form designer class (formname.designer.cs) add this :

this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Login_KeyPress);

and add this code to backbone code (formname.cs):

void Login_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)13)
            MessageBox.Show("ENTER has been pressed!");
        else if (e.KeyChar == (char)27)
            this.Close();
    }