开发者

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:

  • Intercepting KeyDown event 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 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.)


Handle PreviewKeyDown and cancel the event.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜