Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force application to shut down (.net)

Tags:

.net

shutdown

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

like image 766
Duncan Avatar asked Oct 28 '08 10:10

Duncan


3 Answers

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

like image 119
Alan Avatar answered Oct 01 '22 06:10

Alan


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

System.Environment.ExitCode = 1
Application.Exit()
like image 28
Ray Lu Avatar answered Oct 01 '22 05:10

Ray Lu


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.

like image 31
Hallgrim Avatar answered Oct 01 '22 05:10

Hallgrim