Monday, February 11, 2008

Return an exit code from a C# Windows Application

To exit an Windows Forms Application, we have the option to use Application.Exit() or the System.Environment.Exit().

The difference is discussed here (http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx) and the suggestion was made to use System.Environment.Exit() for console applications since it can accept an exit code which will be returned to the Operating System.

But for Windows applications, what should we do ?

I have tried to modify the Main function definition so it will have a return value, a lesson learned from C/C++ old days, then add a property to my main form to indicate if my application would report a success or failure report

And so, my Main function will look like this :

 

        [STAThread]
       
static int Main(string[] arguments)
        {

            Application.EnableVisualStyles()
;
           
Application.SetCompatibleTextRenderingDefault(false);

           
MainForm mainForm = new MainForm();
            Application.Run(mainForm)
;

           
//return exit code
            // 0  : no problem
            // -1 : error occured

           
int exitCode = mainForm.Succeeded == true ? 0 : -1;
            return
exitCode;
           

       
}

 

This approach can be extended to report different exit codes for different scenarios (think about MSBuild or NAnt exit codes).

1 comment:

Anonymous said...

Very useful! Saved hours of experiments! Thank you!