k1f1 k1f1 - 1 month ago 24
C# Question

Detect Enter Key C#

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

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