Question

I am using VSTS 2008 + .Net 3.5 + C# to develop Windows Forms application. My confusion is, seems Application.Exit does not force application to terminate? If not, which method should I call to make application terminate?

EDIT 1:

Normally the main method is like this, how to exit Main function gracefully without calling Environment.Exit?

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        try
        {
            Application.Run(new Form1());
        }
        catch (Exception ex)
        {
            Console.WriteLine (ex.Message);
        }
    }

thanks in advance, George

Was it helpful?

Solution

Application.Exit really just asks the message loop very gently.

If you want your app to exit, the best way is to gracefully make it out of Main, and cleanly close any additional non-background threads.

If you want to be brutal... Environment.Exit or Environment.FailFast? note this is harsh - about the same as killing your own Process.

OTHER TIPS

Try the following:

Process.GetCurrentProcess().Kill();

Environment.Exit doesn't work with Winforms and Environment.FailFast throws its own exception.

If your application does not exit gracefully when you call Application.Exit there is (obviously) something that prevents it from doing so. This can be anything from a form setting e.Cancel = true in the FormClosing event, to a thread that is not a background thread that is still running. I would advice you to carefully research exactly what it is that keeps your process alive, and close that in a nice manner. That should make your application close nicely as well.

Typically, in a winforms application, it should be sufficient to close the main form.

I use

if (System.Windows.Forms.Application.MessageLoop)
{
   // Use this since we are a WinForms app
   System.Windows.Forms.Application.Exit();
}
else
{
   // Use this since we are a console app
   System.Environment.Exit(1);
}

from http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx

I had the same problem when I discovered opening a new form/window within the program, and only HIDING that second form (not closing it), would prevent the main form from properly quitting via Application.Exit();

There are two solutions in this case. First is to simply use Close() on the main form instead of Application.Exit(). Second solution is to use the following code:

if (secondForm != null && !secondForm.IsDisposed) secondForm.Dispose();

I found that simply all you need to do is insted of doing application.exit and all that you just have to do is put in End Simply enough the End command closes it

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top