views:

407

answers:

2

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. http://stackoverflow.com/questions/419596/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.

A: 

There may be an easier way, but you could do it with the hash code. Keys.Escape is another option, but sometimes I cannot get that to work for some reason. You didn't specify a language so here is an example in VB.NET:

Private Sub someTextField_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles someTextField.KeyPress

    If e.KeyChar.GetHashCode = 1769499 Then ''this number is the hash code for escape on my computer, do not know if it is the same for all computers though.
        MsgBox("escape pressed") ''put some logic in here that determines what ever you wanted to know about your "active control"
    End If

End Sub
typoknig
Thanks for replying. The language I am interested in is C#.I am looking for a generic solution to this problem. I don't want to specific code for every control.
Markus2k
A: 

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.

Abe Heidebrecht
This works for me. However not in all cases. In particular, I am using Telerik's DataGrid control. If a cell has a combo box, and it is expanded, and then I hit Escape, then the Escape key is not propagated to the Window. However, if the ComboBox is not expanded, but in edit mode, then the Escape key is propagated. I think it may be a bug with the control. Your suggestion do work.
Markus2k