Aki24x
Aki24x

Reputation: 1068

How to prevent from closing window with "Enter" key while the focus in editable control in WPF

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:

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?

Upvotes: 2

Views: 4702

Answers (3)

Dmitry Melnikov
Dmitry Melnikov

Reputation: 96

You have to set the property IsDefault of the Ok button to false.

Then the click event of the button will be invoked only when the Ok button gets the focus and then by pressing the Enter key or by clicking on it.

Closing the dialog window is automatically activated by setting the DialogResult property, to true or false does not matter.

Upvotes: 1

steinar
steinar

Reputation: 9653

If looking for this particular behavior I would just simply set some boolean value to true in the KeyDown event handler the first time Enter gets hit (rather than switching the focus). Then, on the next KeyDown event, 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 the OnKeyDown method 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.)

Upvotes: 2

Joel Lucsy
Joel Lucsy

Reputation: 8706

Handle PreviewKeyDown and cancel the event.

Upvotes: 2

Related Questions