27
votes

I want to ask the user before closing the application. I'm using C# .NET 4.0 WPF. I can do it in windows forms, but not in WPF. Event is fired when the user want to close the app. Message box appears, bun no matter which button is pressed (Yes or No) the application always closes. Why? Where is the mistake?

It works, but only when the user presses the "X". When the user presses the close button with Application.Current.Shutdown(); it is not working.

private void MainWindowDialog_Closing(object sender,
    System.ComponentModel.CancelEventArgs e)
{
    MessageBoxResult result = MessageBox.Show("Do you really want to do that?",
        "Warning", MessageBoxButton.YesNo, MessageBoxImage.Question);
    if (result == MessageBoxResult.No)
    {
        e.Cancel = true;
    }
}
4
try to insert breakpoint and debug this codeAndrey
The example you posted works fine for me. Maybe the issue is in a different part of the code?Alex McBride

4 Answers

34
votes

The Closing event cannot be cancelled if you call Application.Current.Shutdown(). Just call the Window.Close() method instead, which will give you a chance to veto the close operation. Once all your program's windows have closed the application will shutdown automatically.

For more information checkout the Application Management page on MSDN.

9
votes

Just call YourMainWindow.Close() and use the Closing event as described before.

8
votes
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Are you sure to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        e.Cancel = false;
    else
        e.Cancel = true;
}
1
votes

Why don't you just ask the user whether he wants to close the application, and then call Application.Current.Shutdown() like this:

private void closeButton_Click(object sender, RoutedEventArgs e)
{
    if (MessageBox.Show("Do you want to exit?", "Confirm",
        MessageBoxButton.YesNo) == MessageBoxResult.Yes)
    {
        Application.Current.Shutdown();
    }
}