How do I properly exit a C# application?
c#, exit, winforms
Solution
From MSDN:
Application.Exit
Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.
Environment.Exit
Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.
This article, Application.Exit vs. Environment.Exit, points towards a good tip:
You can determine if `System.Windows.Forms.Application.Run` has been called by checking the `System.Windows.Forms.Application.MessageLoop` property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
if (System.Windows.Forms.Application.MessageLoop)
{
// WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Console app
System.Environment.Exit(1);
}
Reference: Why would Application.Exit fail to work?
Problem
I have a published application in C#. Whenever I close the main form by clicking on the red exit button, the form closes but not the whole application. I found this out when I tried shutting down the computer and was subsequently bombarded by lots of child windows with `MessageBox` alerts I added. I tried `Application.Exit` but it still calls all the child windows and alerts. I don't know how to use `Environment.Exit` and which integer to put into it either. Also, whenever my forms call the `FormClosed` or `FormClosing` event, I close the application with a `this.Hide()` function; does that affect how my application is behaving?