Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not close a form when user presses enter key inside a text box

Having a TextBox control (DevExpress TextEdit to be precise) inside a WinForms form, I do not want the form to close when the user presses the enter key, if the focus is inside the text box.

I thought

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

would be sufficient, but it seems to be ignored and the form still closes.

My question is:

How to intentionally ignore the enter inside a single line text box control so that the form stays open?

Solution

The solution of Botz3000 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;
like image 761
Uwe Keim Avatar asked Jan 16 '23 12:01

Uwe Keim


1 Answers

Update: Try handling the PreviewKeyDown event, too. The MSDN documentation explains it pretty well in the Remarks section. By setting IsInputKey to true, you can override the default behavior so that your TextBox can handle the key. You'll need to do this in PreviewKeyDown and then handle the key as you already do in KeyDown.

EDIT: Not working: Previously suggested EnterMoveNextControl property

like image 120
Botz3000 Avatar answered Jan 31 '23 01:01

Botz3000