tags:

views:

740

answers:

3

Hi

I'm looking to force my application to shut down, and return an Exit code. Had a look on MSDN and I can see that in WPF the Application has a Shutdown method which takes an error code as a parameter, but there doesn't appear to be one for System.Windows.Forms.Application.

I can see Application.Exit() but not a way to pass back an error code.

Does anyone know off-hand if this is possible?

Thanks

+4  A: 

You can use System.Environment.Exit(yourExitCode).

Alan
Any reason to use Environment.Exit over Application.Exit besides error codeS?
Sekhat
Application.Exit needs be used in Winforms apps, environment.exit() can be used in non-GUI programs.
Matt Warren
+1  A: 

set the ExitCode property in the System.Environment class and when exitting. e.g.

System.Environment.ExitCode = 1
Application.Exit()
codemeit
+1  A: 

Add a ExitCode property (or something similar) to your form class:

class MyForm : Form {
  public int ExitCode { get; set; }

  void ShutDownWithError(int code) {
    ExitCode = code;
    Close();
  }
}

Somewhere in your code you have:

static void Main() {
  // ...
  MyForm form = new MyForm();
  Application.Run(myForm);
}

Change that into:

static void Main() {
  // ...
  MyForm myForm = new MyForm();
  Application.Run(myForm);
  Environment.Exit(myForm.ExitCode);
}

When the ShutdownWithError method is called on your form, you will Close the main form. This will jump out of the loop started with Application.Run. Then you just fetch the exit code and kill the process with Environment.Exit.

Hallgrim
Thanks, I think our case is a little more complicated because we are needing to shut down in the global exception handler. But the principle is the same, I think.
Duncan