How not to close the form when the user presses the enter key inside the text field

Having a TextBox control (more precisely, DevExpress TextEdit ) inside a WinForms form, I don’t want to close the form when the user presses the enter key if the focus is inside the text field.

I thought

 filterTextBox.KeyDown += (sender, e) => e.Handled = e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter; 

would be enough, but that seems to be ignored, and the form is still closing.

My question is:

How to deliberately ignore input inside a single-line text field control so that the form remains open?

Decision

Botz3000 solution worked for me:

 filterTextBox.PreviewKeyDown += (sender, e) => e.IsInputKey = e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter; filterTextBox.KeyDown += (sender, e) => e.Handled = e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter; 
+4
source share
3 answers

Refresh . Try to handle the PreviewKeyDown event. The MSDN documentation explains this well in the "Notes" section. By setting IsInputKey to true, you can override the default behavior so that your TextBox can handle the key. You need to do this in PreviewKeyDown , and then process the key, as you already did in KeyDown .

EDIT: Doesn't work: previously proposed EnterMoveNextControl property

+6
source

Based on your decision, guys, during normal processing of RichTextBox PreviewKeyDown was pretty good.

 private void rtbNote_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { e.IsInputKey = e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter; } 
+2
source

Without trying to do this, I think that I would just set the boolean value in KeyDown text field, then in closing the form I would check this Boolean and cancel closing the form if it is installed (and then reset boolean).

+1
source

Source: https://habr.com/ru/post/1415921/


All Articles