Missing "KeyPress" event for WinForms text box?

I am trying to add a "KeyPress" event to a text box (WinForm)

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

and here inside the "CheckKeys":

 private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e) { if (e.KeyChar == (char)13) { // Enter is pressed - do something } } 

The idea here is that after the text field is in focus and the 'Enter' button is pressed, something will happen ...

However, my car cannot find the KeyPress event. Is there something wrong with my codes?

UPDATE:

I also tried putting KeyDown instead of KeyPress:

 private void textBox1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == Key.Return) // Enter is pressed - do something } } 

Still not working though ...

+6
c # winforms keyboard-events textbox
source share
3 answers

You mix class libraries, don't use Windows Forms classes in a WPF project. Do it like this:

  public partial class Window1 : Window { public Window1() { InitializeComponent(); this.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { MessageBox.Show("Enter!"); e.Handled = true; } } } 
+9
source share

Have you looked at the KeyPress documentation ? It states that the KeyPress event is not generated by uncharacteristic keys; however, uncharacteristic keys do increment KeyDown and KeyUp events. Using one of these events should work instead.

+6
source share

try to follow the steps that it will work, bcoz, I tested it.

  • select the text box, right-click it and select properties.
  • click on an event, then double click on KeyPress
  • enter the following code.

     private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13) { //press Enter do Something Like i have messagebox below to show "wow" MessageBox.Show("wow"); } else { } } 
-4
source share

All Articles