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
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

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)Thats it you are done.
{
if (altF4Pressed)
{
e.Cancel = true;
altF4Pressed = false;
}
}
Why not just set the handle event to true in the window key down?
ReplyDeleteprivate void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Alt && e.SystemKey== Key.F4)
{
e.handle=true;
}
}
moca is right, that's much simpler, however, thanks for your post
ReplyDelete