Search code examples
.nettermination

How to gracefully exit this application?


In order to not show a form in C#.NET when first starting the application I have this:

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        SomethingForm frmSomething = new SomethingForm();

        Application.Run();
    }

It is a one form application and the SomethingForm is the the parent form which has a Button to exit which currently calls the following Application.ExitThread();. This button is the only way to exit the application.

Now I know this is not graceful termination, but it was the only way I could get it to work when testing. It's now causing some problems with leaving the icon in the system tray after exit.

So how do I GRACEFULLY terminate this application?


Solution

  • Simply call this.Close() from the Form. Assuming that's the only Form, the application should exit gracefully.

    A slightly less graceful way is to use Application.Exit(). The problem with this is form closing events aren't raised (fixed after .NET 1.1).