Select Page

After being disappointed with Android development, I’m ramping back up on WPF.  I have a full screen app and no buttons visible, so I would like to implement the ESC key to close the window instead of using ALT+F4.

Looking around the net, I can do this by putting a dummy button on my View that knows how to close the View.  I can then make that button invisible, but set it’s IsCancel property, which triggers the event when ESC is pressed.  I could also create my own class that implements ICommand.

But really, I found something far simpler and it feels a lot cleaner.  In the XAML, you do the following:

 <CommandBinding Command="Close" Executed="OnCloseExecuted" />
 <KeyBinding Command="Close" Key="Esc" />

You code-behind looks like this:

private void OnCloseExecuted(object sender, ExecutedRoutedEventArgs e)

Voila!  I got this tip from Wallace Kelly’s blog – thanks Wallace!