I want the Escape key to close my WPF window. However if there is a control that can consume that Escape key, I don't want to close the Window. There are multiple solutions on how to close the WPF Window when ESC key is pressed. eg. How does the WPF Button.IsCancel property work?
However this solution closes the Window, without regard to if there is an active control that can consume the Escape key.
For eg. I have a Window with a DataGrid. One of the columns on the dataGrid is a combobox. If I am changing the ComboBox, and hit Escape, then the control should come out of editing of the comboBox (Normal Behavior). And if I now hit Escape again, then the Window should close. I would like a generic solution, instead of writing a lot of custom code.
If you can provide a solution in C# it would be great.
You should just use the KeyDown
event instead of the PreviewKeyDown
event. If any child of the Window
handles the event, it won't be bubbled up to the Window (PreviewKeyDown
tunnels from the Window
down), and therefore your event handler won't be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With