12

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.

slfan
  • 8,950
  • 115
  • 65
  • 78
k1f1
  • 433
  • 3
  • 8
  • 16

4 Answers4

12

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();
    }
7

This is because when you press Enter TextChanged event won't fire.

Renatas M.
  • 11,694
  • 1
  • 43
  • 62
0
private void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
 {
            if (e.Key == Key.Enter)
            {
                MessageBox.Show("Enter key pressed");
            }
            else if (e.Key == Key.Space)
            {
                MessageBox.Show("Space key pressed");
            }
}

Use PreviewKeyDown event to detect any key before shown in textbox or input

0
void cbServer_PreviewKeyDown(object sender, System.Windows.Forms.PreviewKeyDownEventArgs e)
    {

        // Check if User Presses Enter
        if (e.KeyCode == System.Windows.Forms.Keys.Return)
        {
            // Here: user pressed ENTER key

        }
        else
        {
            // Here: user did not press ENTER key
        }
    }
Budapest
  • 105
  • 7