Reputation: 31
What is the best way to close an entire windows application form when the application is closed? Apparently after I exit the application, the application is still running.
Upvotes: 0
Views: 250
Reputation: 1996
Ideally, you should find out WHY your app is still hanging around as per Fredkrik's answer. However, if you want to force your app exit, Environment.Exit is what you want. Application.Exit only exits the current message pump (although admittedly you will only have on unless you have called Application.Run more than once).
From the docco:
Environment.Exit Method Terminates this process and gives the underlying operating system the specified exit code.
Application.Exit Method Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
Upvotes: 0
Reputation: 31231
Not the prettiest way of closing a program but if you just want to end the process completely just run Process.Kill()
on itself. If there are any threads running that haven't finished it might be best to gracefully close them first. If you don't care about what hasn't finished this will do the trick:
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName.Contains("appname"))
{
p.Kill();
}
}
Upvotes: 0
Reputation: 158309
If the application is still running after the application's main form has been closed, you have some thread hanging around that is not done with it's job. You should identify that and make sure it closes gracefully. When that is done, your application process should go away nicely when you close the main form, without the need to bring out weapons and shoot it.
Upvotes: 4
Reputation: 28687
Following Bali's comment, use:
Application.Exit()
Details at http://msdn.microsoft.com/en-us/library/ms157894.aspx (emphasis mine):
The Exit method stops all running message loops on all threads and closes all windows of the application. This method does not necessarily force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. To exit a message loop for the current thread only, call ExitThread.
Upvotes: 2