21

How do i return a non-zero exit code from a Windows Forms application.

Application.Exit() is the preferred way to exit the application, but there is no exit code argument.

I know about Environment.Exit(), but that is not a nice way to close the application loop....

Fedearne
  • 7,049
  • 4
  • 27
  • 31

3 Answers3

32

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);
    } 
}
Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
  • Great example, very close to what i need. – Fedearne Jul 08 '10 at 08:54
  • 1
    make sure your exitcodes are positive integers, or else %ERRORLEVEL% on command prompt will return you 0 for negative codes. So in the sample, exitCode should be uint and ExitApplication should take uint as well. – Nitin Chaudhari Dec 20 '11 at 07:22
  • Thank You, exactly what I needed. – VivekDev Aug 02 '16 at 08:51
  • **WRONG ANSWER.** `Environment.Exit()` does not terminate a Winforms application properly. See https://stackoverflow.com/questions/13046019/winforms-application-exit-vs-environment-exit-vs-form-close – ivan_pozdeev Nov 14 '22 at 11:47
16

If your main method returns a value you can return the exit code there.

Otherwise you can use Environment.ExitCode to set it. E.g. to set the would-be exit code when the main form is about to close:

private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
    Environment.ExitCode = <exit code>;
}

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
  • 2
    +1 Great quick way to accomplish this. I have however a very big app, with quite a few possible exit codes and alot of different ways to exit. I will go with the example by VirtualBlackFox in my current application. – Fedearne Jul 08 '10 at 08:53
-1

Go to event tab in your form and in click place double click on it and then in code place write Environment.Exit(0);

Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
behnam
  • 7
  • 1