Tuesday, May 18, 2010

Closing a window or dialog box when an escape key is pressed in WPF

When you pop up a dialog box, users expect to be able to press the ESC key to close the dialog box. It can be quite annoying otherwise. In WPF, the easiest way to do that is to set the IsCancel property of your close button like this:

<Button Content="Close" Click="OnClose" IsCancel="True" />

On a recent project, however, I did not have a close button to set IsCancel on. The solution is to use WPF commands and input gestures. Here is an example:

<Window.CommandBindings>
   <CommandBinding Command="Close" Executed="OnCloseCmdExecuted" />
</Window.CommandBindings>

<Window.InputBindings>
   <KeyBinding Command="Close" Key="Escape" />
</Window.InputBindings>

private void OnCloseCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
   this.Close();
}

No comments:

Post a Comment