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; } }
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.
Just call YourMainWindow.Close() and use the Closing event as described before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With