Search code examples
c#winformstextboxdevexpress

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;

Solution

  • 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