Monday, December 14, 2009

Disabling Alt+F4 key press in WPF

Introduction

This article shows you how to disable default behaviour of closing current window of Alt+F4 key press.Although very basic, when i googled for it i could not find a direct answer. This article will help beginners like me.

Using the code

In your Window code have a bool variable altF4Pressed and handle key down event with the following method
Collapse
 private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Alt && e.SystemKey== Key.F4)
{
altF4Pressed = true;
}
}

Now handle closing event of window with following method

Collapse
       private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (altF4Pressed)
{
e.Cancel = true;
altF4Pressed = false;
}
}
Thats it you are done.

2 comments:

  1. Why not just set the handle event to true in the window key down?

    private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
    if (Keyboard.Modifiers == ModifierKeys.Alt && e.SystemKey== Key.F4)
    {
    e.handle=true;
    }
    }

    ReplyDelete
  2. moca is right, that's much simpler, however, thanks for your post

    ReplyDelete