Exit code from Windows Forms app

Application.Exit just force the call to Application.Run (That is typically in program.cs) to finish. so you could have :

Application.Run(new MyForm());
Environment.Exit(0);

and still inside your application call Application.Exit to close it.

Small sample

class Program
{
    static int exitCode = 0;

    public static void ExitApplication(int exitCode)
    {
        Program.exitCode = exitCode;
        Application.Exit();
    }

    public int Main()
    {
        Application.Run(new MainForm());
        return exitCode;
    }
}

class MainForm : Form
{
    public MainForm()
    {
        Program.ExitApplication(42);
    } 
}

If your main method returns a value you can return the exit code there. Otherwise you can use Environment.ExitCode to set it.

Tags:

C#

.Net

Winforms