562

How is one supposed to exit an application such as 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.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122

19 Answers19

895

To exit your application you can call

System.Windows.Application.Current.Shutdown();

As described in the documentation to the Application.Shutdown method you can also modify the shutdown behavior of your application by specifying a ShutdownMode:

Shutdown is implicitly called by Windows Presentation Foundation (WPF) in the following situations:

  • When ShutdownMode is set to OnLastWindowClose.
  • When the ShutdownMode is set to OnMainWindowClose.
  • When a user ends a session and the SessionEnding event is either unhandled, or handled without cancellation.

Please also note that Application.Current.Shutdown(); may only be called from the thread that created the Application object, i.e. normally the main thread.

Community
  • 1
  • 1
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
  • 9
    As I pointed out it's not weird. In WPF Application is a static class. Application.Current is a reference to your currently running Application. – TimothyP May 12 '10 at 15:42
  • 4
    In my opinion, it is a little weird in the sense that this isn't obvious at first glance, and it deviates just enough from past models to throw people off. It makes perfect sense that it works of course. – Brian MacKay May 12 '10 at 15:52
  • Put it simple: because if your last window is closed with... this.Close() ...The application will be shutdown, provided that you didn't change the ShutdownMode. – HelloSam Sep 21 '11 at 03:26
  • 24
    If you call `Application.Current.Shutdown();` your fonction will not return immediately. You need to call `return;` as well for this. – Erwin Mayer Apr 18 '12 at 10:06
  • 2
    I have used this where from one window pop up another window and, in that window's window_closed event I added this code. all the windows disappear, but the program still runs beyond where after the pop up is created. – diyoda_ Jan 05 '13 at 17:37
  • Is Shutdown supposed to call OnExit? Or do I need to call that? – tofutim May 16 '13 at 02:32
  • 10
    @TimothyP No `Application` is NOT a static class. Having a `Application.Current` static member does not mean it is static. Instead, it is an normal class that can be derived. – Earth Engine Nov 04 '16 at 03:41
192

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John
  • 6,503
  • 3
  • 37
  • 58
  • 5
    `Environment.Exit()` needs at least one parameter, an exit code. Use `Environment.Exit(0)` if you are not concerned about the exit code. – gbmhunter May 23 '13 at 04:30
  • 32
    This method actually closed everything. My app was leaving something running (the form was closing, but a process was still running) with `Application.Current.Shutdown();` – gbmhunter May 23 '13 at 04:32
  • 5
    Environment.Exit is definitely the right way to ensure shutdown of an application. With Application.Current.Shutdown you can easily end up with the application running on indefinitely if you have code that pushes itself back into the dispatcher. – Marcus Andrén Sep 19 '13 at 10:14
  • As equal as Application.exit(0); – Abdul Saleem Feb 17 '15 at 06:35
  • 2
    With `Application.Current.Shutdown();` my `Closing` event was called, when I simply wanted to shutdown my app immediately. So `Environment.Exit(0);` was the better choice. – FredM Nov 08 '18 at 09:37
83

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.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Allen Pestaluky
  • 3,126
  • 2
  • 20
  • 22
  • 3
    +1 I decided to go with this one, especially since I need to save open files before actually quitting the application. – AgentKnopf Jun 07 '13 at 06:23
  • 4
    One important thing to note here is the fact that Allen pointed out a very important fact: all other owned windows will be shut down. You have to make sure that you declare ownership. If you have a window that is running and then you open another window but do not show it yet, after you close the active window, the hidden window will force application to keep running. You will have a potential memory leak unless you close that window through other means (task manager, etc). I've tested this. – B.K. Feb 08 '14 at 01:10
  • @B.K. so in such a case will using Application.Current.Shutdown() instead of this.close() close the hidden windows as well? – Somanna Oct 26 '20 at 16:27
40

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);
Kylo Ren
  • 8,551
  • 6
  • 41
  • 66
29

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

Brian MacKay
  • 31,133
  • 17
  • 86
  • 125
20

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.

B.K.
  • 9,982
  • 10
  • 73
  • 105
18

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 called 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

burgund
  • 357
  • 1
  • 5
  • 12
  • 1
    "Environment.Exit(0);" worked for me. The most voted answer with "System.Windows.Application.Current.Shutdown();" didn't worked as the application tried to run the next code lines. Upvoted yours. Thanks – Ricardo Araújo Jul 16 '20 at 16:18
17

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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TimothyP
  • 21,178
  • 26
  • 94
  • 142
12

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.

tobre
  • 1,347
  • 3
  • 21
  • 53
Ali Yousefi
  • 2,355
  • 2
  • 32
  • 47
  • This seems incomprehensible: *"in process always works"*. Can you fix it? Or at least explain here in comments what you mean? – Peter Mortensen May 19 '18 at 19:34
  • This is also partly incomprehensible: *Just care about an application that has save data in files from another thread.* Can you fix it? Or at least explain here in comments what you mean? – Peter Mortensen May 19 '18 at 19:35
  • Are you using Google Translate? – Peter Mortensen May 19 '18 at 19:36
  • no I don't, my mean is when application is running as multi thread and you using Process.Kill it will works,but another way like this.close not working in multithread applications when another thread is running. – Ali Yousefi May 20 '18 at 10:51
7
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);
}
Ravi
  • 79
  • 1
  • 1
7

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
wuminqi
  • 349
  • 1
  • 2
  • 6
  • 9
    I don't understand this. We can get user confirmation before calling `Application.Current.Shutdown()` however. – Amsakanna May 13 '10 at 08:45
  • 3
    I don't see why you should confirm. Too many confirmations is a very bad thing. The fact that somebody took the effort to click to open the File menu, move all the way down to the bottom of the File menu and then click Exit, is pretty much confirmed that they no longer wish to use the application. –  May 13 '10 at 11:09
  • Veer: In my case, the confirmation window do appear, but even when you choose "cancel" in the confirmation, the main APP exits. – wuminqi May 14 '10 at 06:05
  • 7
    J-T-S:This is better to be designed case by case. Our app, if there are jobs running, the force exit will cause damages, so we better to let them informed in the confirmation dialog – wuminqi May 14 '10 at 06:06
7

Try

App.Current.Shutdown();

For me

Application.Current.Shutdown(); 

didn't work.

Iwona Kubowicz
  • 364
  • 3
  • 15
3

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 });
    }
}
Anders
  • 17,306
  • 10
  • 76
  • 144
2

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

Soumya Mahunt
  • 2,148
  • 12
  • 30
2

App.Current.Shutdown();
Write that where you need to.

1

If you are using Application.Current.Shutdown() to exit the application, you may get a System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it. if you are invoking it from a different thread. To solve this, you can wrap the call like this

Application.Current.Dispatcher.Invoke(() => Application.Current.Shutdown());
datchung
  • 3,778
  • 1
  • 28
  • 29
1
if (System.Windows.Forms.Application.MessageLoop) 
{
    // WinForms app
    System.Windows.Forms.Application.Exit();
    system.Environment.Exit(1);
}
Markus Meyer
  • 3,327
  • 10
  • 22
  • 35
  • 1
    Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. – Saeed Zhiany Jul 24 '22 at 03:59
  • The question is about WPF. The Environment.Exit() code is all the OP may need, and the exit code 1 could signify an error, as 0 is the standard to convey the program's successful execution. – TheWaterWave222 Jan 01 '23 at 19:05
-2

Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

stop-cran
  • 4,229
  • 2
  • 30
  • 47
  • 3
    Welcome to SO, Alpha-LIon! Code-only answers are discouraged here, as they provide no insight into how the problem was solved. Please update your solution with an explanation of how your code solves the OP's problem :) – Joel Oct 30 '18 at 01:51
-3

From xaml code you can call a predefined SystemCommand:

Command="SystemCommands.MinimizeWindowCommand"

I think this should be the prefered way...

  • 1
    Minimize != exit application. I don't see an exit app option in that list. Seems more window management and close window doesn't necessarily mean close app. https://msdn.microsoft.com/en-us/library/system.windows.systemcommands%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 – kenny Jun 16 '18 at 09:58