[c#] How do I exit a WPF application programmatically?

In the few years I've been using C# (Windows Forms), I've never used WPF. But, now I love WPF, but I don't know how I am supposed to exit my application when the user clicks on the Exit menu item from the File menu.

I have tried:

this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();

Among many others. Nothing works.

This question is related to c# .net wpf shutdown

The answer is


As wuminqi said, Application.Current.Shutdown(); is irreversible, and I believe it is typically used to force an application to close at times such as when a user is logging off or shutting down Windows.

Instead, call this.close() in your main window. This is the same as pressing Alt + F4 or the close [x] button on the window. This will cause all other owned windows to close and will end up calling Application.Current.Shutdown(); so long as the close action wasn't cancelled. Please see the MSDN documentation on Closing a Window.

Also, because this.close() is cancellable you can put in a save changes confirmation dialog in the closing event handler. Simply make an event handler for <Window Closing="..."> and change e.Cancel accordingly. (See the MSDN documentation for more details on how to do this.)


From xaml code you can call a predefined SystemCommand:

Command="SystemCommands.MinimizeWindowCommand"

I think this should be the prefered way...


Try

App.Current.Shutdown();

For me

Application.Current.Shutdown(); 

didn't work.


Summarizing, there are a few ways to do that.

1) Killing the process, which skip the finalization, error handling etc.:

Process.GetCurrentProcess().Kill();

2) Shutting down current application, which is probably the proper way because it calls the exit events:

Application.Current.Shutdown();

or

this.Shutdown();

(when clled in an instance of App-class)

3) Closing current app (all forms have to be closed/finished earlier):

this.Close(); 

(when clled in an instance of App-class)

4) Exiting the environment, which terminates the app:

Environment.Exit(0);

Also, You may want to read about exit statusses here


Here's how I do mine:

// Any control that causes the Window.Closing even to trigger.
private void MenuItemExit_Click(object sender, RoutedEventArgs e)
{
    this.Close();
}

// Method to handle the Window.Closing event.
private void Window_Closing(object sender, CancelEventArgs e)
{
    var response = MessageBox.Show("Do you really want to exit?", "Exiting...",
                                   MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
    if (response == MessageBoxResult.No)
    {
        e.Cancel = true;
    }
    else
    {
        Application.Current.Shutdown();
    }
}

I only call for Application.Current.ShutDown() from the main application window, all other windows use this.Close(). In my main window, Window_Closing(...) handles the top right x button. If any of the methods call for window closer, Window_Closing(...) grabs the event for shut down if user confirms.

The reason I do in fact use Application.Current.Shutdown() in my main window is that I've noticed that if a design mistake was made and I haven't declared a parent of one of my windows in an application, if that window is opened without being shown prior to the last active window closing, I'm left with a hidden window running in the background. The application will not shut down. The only way to prevent complete memory leak is for me to go into the Task Manager to shut down the application. Application.Current.Shutdown() protects me from unintended design flaws.

That is from my personal experience. In the end, use what is best for your scenario. This is just another piece of information.


Use any of the following as needed:

1.

 App.Current.Shutdown();
OR
 Application.Current.Shutdown();

2.

 App.Current.MainWindow.Close();
OR
 Application.Current.MainWindow.Close();

Above all methods will call closing event of Window class and execution may stop at some point (cause usually applications put dialogues like 'are you sure?' or 'Would you like to save data before closing?', before a window is closed completely)

3. But if you want to terminate the application without any warning immediately. Use below

   Environment.Exit(0);

There should not be an Application.ShutDown(); or .Exit() message.

Application is a static class. It does not refer to the current application. You need to get to the current application and then shut it down like this:

Application.Current.Shutdown();

Another way you can do this:

System.Diagnostics.Process.GetCurrentProcess().Kill();

This will force kill your application. It always works, even in a multi-threaded application.

Note: Just be careful not to lose unsaved data in another thread.


private void _MenuExit_Click(object sender, RoutedEventArgs e)
{
   System.Windows.Application.Current.MainWindow.Close();
}

//Override the onClose method in the Application Main window

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    MessageBoxResult result =   MessageBox.Show("Do you really want to close", "",
                                          MessageBoxButton.OKCancel);
    if (result == MessageBoxResult.Cancel)
    {
       e.Cancel = true;
    }
    base.OnClosing(e);
}

According to my understanding, Application.Current.Shutdown() also has its drawback.

If you want to show a confirmation window to let users confirm on quit or not, Application.Current.Shutdown() is irreversible.


This should do the trick:

Application.Current.Shutdown();

If you're interested, here's some additional material that I found helpful:

Details on Application.Current

WPF Application LifeCycle


If you really need it to close out you can also use Environment.Exit(), but it is not graceful at all (more like ending the process).

Use it as follows:

Environment.Exit(0)

If you want to exit from another thread that didn't create the application object, use: System.Windows.Application.Current.Dispatcher.InvokeShutdown()


Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;


Caliburn micro flavoured

public class CloseAppResult : CancelResult
{
    public override void Execute(CoroutineExecutionContext context)
    {
        Application.Current.Shutdown();
        base.Execute(context);
    }
}

public class CancelResult : Result
{
    public override void Execute(CoroutineExecutionContext context)
    {
        OnCompleted(this, new ResultCompletionEventArgs { WasCancelled = true });
    }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to shutdown

Android Service Stops When App Is Closed Executing a batch script on Windows shutdown Stop MySQL service windows How do I exit a WPF application programmatically? How can I get the Windows last reboot reason How do I shutdown, restart, or log off Windows via a bat file? How to shut down the computer from C#