views:

145

answers:

4

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

It works, but only when user press "X". When user press 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;
    }
}
A: 

Forgive me but here is a vb answer I used a converter to get the following C code:

private void Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
{
    if (MessageBox.Show("Are you sure to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        e.Cancel = false;
    }
    else
    {
        e.Cancel = true;
    }
}
halfevil
It works, but only when user press "X". When user press button with Application.Current.Shutdown(); it is not working.
Hooch
A: 

for me it worked

  private void Window_Closing(object sender, 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;
        } 

    }
saurabh
It works, but only when user press "X". When user press button with Application.Current.Shutdown(); it is not working.
Hooch
you simply can not control this , if you call Application.Current.Shutdown(), Application is eventually going to be exit.
saurabh
+2  A: 

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

Gustavo Cavalcanti
That is, don't use Application.Current.Shutdown().
Curt Nichols
+5  A: 

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.

Fara