Discovery Enter C # Key

I have the following code that does not show MessageBox when pressing Enter / Return.

For any other key (e.g. 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: over the code, I thought the problem was in _Keydown, even so I just posted this.

+7
source share
3 answers

This is because when you press Enter TextChanged event does not fire.

+5
source

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

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

and add this code to the base 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
source
 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 the PreviewKeyDown event to detect any key before displaying in a text box or entering

0
source

All Articles