WPF Application Exit Codes
When a program exits, it can return an integer that describes its closing status. Although this is commonly used for command-line utilities, the same system of exit codes can be used by WPF applications.
In a previous article I explained how you can create applications that return an exit code and how to access that code from the command line. The earlier article described the process for a console application. However, the same principles can be used with WPF applications. You can return an integer on closing the program. Unless otherwise specified, the exit code defaults to zero. Usually, any other number indicates an error.
The way in which you specify an exit code depends upon the configuration of the application. If you are using the WPF feature to exit the program automatically, based upon windows being closed, you would normally set the exit code in the Exit event handler. When exiting manually, the code can be supplied using a parameter of the Shutdown method.
Using the Exit Event
If your application closes automatically, you can set the exit code using the event arguments of the Exit event. This event uses an instance of the ExitEventArgs for its event arguments. The type includes the ApplicationExitCode property, which you can set to an integer. If you don't change the value, the exit code defaults to zero.
To demonstrate, create a new WPF application in Visual Studio named, "ExitCodeDemo". Once prepared, open the App.xaml file and attach the Exit event, as shown in the fifth line of the XAML below:
Switch to the code behind the App.xaml and add the following event handler:
private void Application_Exit(object sender, ExitEventArgs e)
e.ApplicationExitCode = 99;
To demonstrate the exit code, save and compile the program. Next, create a new batch file within the same folder as the compiled executable. Name the file, "Test.bat" and include the following commands in the file.
echo The exit code was %ERRORLEVEL%.
Run the batch file from a command prompt. The WPF application will appear. When you close the window, the exit code will be displayed:
When you wish to use the Shutdown method to close your application, you can set the exit code by passing it to the method's parameter. Let's update the program to use this approach. Start by amending the App.xaml to use explicit shutdown mode, as follows:
Remove the handler for the Exit event from the code behind the App.xaml, then modify the main window's XAML to add a button, using the following element:
<Button Width="100" Height="30" Click="Exit_Click">Exit</Button>
Switch to the code behind the window and add the handler method that closes the window with the Shutdown method. The code below shows a shutdown with an exit code of 99.
private void Exit_Click(object sender, RoutedEventArgs e)
Recompile the program and run the batch file to see the results.
14 February 2016