I am trying to set and get the application exit code .
I am trying to do something following :
protected override void OnStartup(StartupEventArgs e)
override the OnExit method, and in the ExitEventArgs you can set that value.
protected override void OnExit(ExitEventArgs e)
{
e.ApplicationExitCode = your_value;
}
Do it like this:
Environment.Exit(110);
This will terminate the current application with exit code 110
.
It works for me with either method (Environment.ExitCode=110
or Environment.Exit(110)
). I hope you are calling the program from the console and not from Visual Studio to then check the ExitCode...
You can do it in Main
method. Just change its return-value-type to int
instead of void
and return your exit-code
static int Main(string[] args) {
// something to do
Console.ReadKey();
return 110;
}
UPDATE:
To create a custom Main
in WPF application, you should follow these steps:
First: unload the project by right-click on it in Solution Explorer and click on Unload Project
Modify the .csproj
file by change the <ApplicationDefinition Include="App.xaml">
to this one: <Page Include="App.xaml">
Now you can create your own Main
method in your project:
Sample Main
method and App
class:
public partial class App : Application {
[STAThread]
public static int Main() {
App app = new App();
app.InitializeComponent();
var i = app.Run();
return i;
}
public App() : base() { }
protected override void OnExit(ExitEventArgs e) {
e.ApplicationExitCode = 110;
base.OnExit(e);
}
}
For WPF, try
Application.Current.Shutdown(110);
Note that the application needs to be running as a console app. This answer is the easiest way I know of; the accepted answer looks more difficult.
An easy test to tell if you're running in console mode: call your app from the command line (make sure your code doesn't shut down right away). The main window should be showing. If you can type another command in the console, your app is not running in its context. The command prompt should be locked, waiting for you to close the window.
You can do this in the following ways...
Application.Current.Shutdown(110); Environment.Exit(10); this.Close();
Shoutdown() returns a code. and Exit() also returns an exit code, but Close() only closes the application.