Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is "Esc" key handled in WPF Window?

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.

like image 657
Markus2k Avatar asked Apr 19 '10 02:04

Markus2k


1 Answers

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.

like image 164
Abe Heidebrecht Avatar answered Sep 28 '22 06:09

Abe Heidebrecht