Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ask the user before closing C# WPF application

Tags:

c#

.net

events

wpf

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;     } } 
like image 794
Hooch Avatar asked Oct 14 '10 16:10

Hooch


2 Answers

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.

like image 165
Alex McBride Avatar answered Sep 23 '22 01:09

Alex McBride


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

like image 20
Gus Cavalcanti Avatar answered Sep 25 '22 01:09

Gus Cavalcanti