Application.Exit

*爱你&永不变心* 提交于 2019-11-26 04:49:15

问题


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


回答1:


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.




回答2:


Try the following:

Process.GetCurrentProcess().Kill();

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




回答3:


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.




回答4:


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




回答5:


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();



回答6:


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



来源:https://stackoverflow.com/questions/1057151/application-exit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!