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
You can use System.Environment.Exit(yourExitCode).
set the ExitCode property in the System.Environment class and when exitting. e.g.
System.Environment.ExitCode = 1
Application.Exit()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With