Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit code from Windows Forms app

Tags:

c#

.net

winforms

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....

like image 668
Fedearne Avatar asked Jul 08 '10 08:07

Fedearne


People also ask

How do I exit Winforms application?

The proper method would be Application. Exit() .

How do you exit an application in Visual Basic?

Just Close() all active/existing forms and the application should exit. ok.


2 Answers

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);
    } 
}
like image 113
Julien Roncaglia Avatar answered Oct 02 '22 06:10

Julien Roncaglia


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

like image 30
Hans Olsson Avatar answered Oct 02 '22 06:10

Hans Olsson