How to prevent from closing window with Enter key while the focus in editable control?
Usually, I make Cancel with IsCancel=True and Ok with IsDefault=True. This is because it will allow users to close a dialog with Enter as OK and Esc as Cancel.
However, the problem is pressing Enter key closes the dialog even a keyboard focus is in an editable control such as TextBox.
The best behavior is pressing Enter key closes dialog only when the keyboard focus is not in an editable control. But, pressing Enter key twice should close the dialog. Otherwise, users need to change keyboard focus to another non-editable control to close with Enter key.
So, as a workaround, I implemented this way:
- Intercepting
KeyDownevent and check
if it’s Enter key. - If so, check if the keyboard focus is
at Ok button. - If so, closes the dialog with Ok
button. Otherwise, change the
keyboard focus to Ok button. So, hit Enter key twice will close the dialog.
This has a problem because the first Enter will change the focus to Ok button, so if the focus is not at the Ok Button, users need to hit Enter twice. This is little different from an ideal behavior. Also, I need to implement this logic to each dialog.
Does someone have a good idea to solve this?
If looking for this particular behavior I would just simply set some boolean value to true in the
KeyDownevent handler the first time Enter gets hit (rather than switching the focus). Then, on the nextKeyDownevent, I’d check if the key hit was Enter and if Enter has been hit before. To implement this in more than one dialog, I would create a generic dialog where I would override theOnKeyDownmethod rather than subscribing to the event, then subclass that dialog.(Having said that, as a user I would not like this behavior at all. I would recommend just ignoring the Enter key altogether when in a text box – that’s what users are used to.)