The lifetime of a WPF application is marked by several events that are raised by Application to let you know when your application has started, has been activated and deactivated, and has been shut down.
This section contains the following subsections.
Splash Screen
Starting an Application
After Run is called and the application is initialized, the application is ready to run. This moment is signified when the Startup event is raised:
using System.Windows; // Application, StartupEventArgs, WindowState
namespace SDKSample
{
public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
// Application is running
...
}
}
}
At this point in an application's lifetime, the most common thing to do is to show a UI.
Showing a User Interface
Most standalone Windows applications open a Window when they begin running. The Startup event handler is one location from which you can do this, as demonstrated by the following code.
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
Startup="App_Startup" />
using System.Windows; // Application, StartupEventArgs
namespace SDKSample
{
public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
// Open a window
MainWindow window = new MainWindow();
window.Show();
}
}
}
Note: |
|---|
The first Window to be instantiated in a standalone application becomes the main application window by default. This Window object is referenced by the Application..::.MainWindow property. The value of the MainWindow property can be changed programmatically if a different window than the first instantiated Window should be the main window. |
When an XBAP first starts, it will most likely navigate to a Page. This is shown in the following code.
<Application
x:Class="SDKSample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="App_Startup" />
using System; // Uri, UriKind, EventArgs, Console
using System.Windows; // Application, StartupEventArgs
using System.Windows.Navigation; // NavigationWindow
namespace SDKSample
{
public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
((NavigationWindow)this.MainWindow).Navigate(new Uri("HomePage.xaml", UriKind.Relative));
}
}
}
If you handle Startup to only open a Window or navigate to a Page, you can set the StartupUri attribute in markup instead.
The following example shows how to use the StartupUri from a standalone application to open a Window.
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
StartupUri="MainWindow.xaml" />
The following example shows how to use StartupUri from an XBAP to navigate to a Page.
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
StartupUri="HomePage.xaml" />
This markup has the same effect as the previous code for opening a window.
You need to handle the Startup event to open a Window if you need to instantiate it using a non-default constructor, or you need to set its properties or subscribe to its events before showing it, or you need to process any command-line arguments that were supplied when the application was launched.
Processing Command-Line Arguments
In Windows, standalone applications can be launched from either a command prompt or the desktop. In both cases, command-line arguments can be passed to the application. The following example shows an application that is launched with a single command-line argument, "/StartMinimized":
wpfapplication.exe /StartMinimized
During application initialization, WPF retrieves the command-line arguments from the operating system and passes them to the Startup event handler via the Args property of the StartupEventArgs parameter. You can retrieve and store the command-line arguments using code like the following.
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
Startup="App_Startup" />
using System.Windows; // Application, StartupEventArgs, WindowState
namespace SDKSample
{
public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
// Application is running
// Process command line args
bool startMinimized = false;
for (int i = 0; i != e.Args.Length; ++i)
{
if (e.Args[i] == "/StartMinimized")
{
startMinimized = true;
}
}
// Create main application window, starting minimized if specified
MainWindow mainWindow = new MainWindow();
if (startMinimized)
{
mainWindow.WindowState = WindowState.Minimized;
}
mainWindow.Show();
}
}
}
The code handles Startup to check whether the /StartMinimized command-line argument was provided; if so, it opens the main window with a WindowState of Minimized. Note that because the WindowState property must be set programmatically, the main Window must be opened explicitly in code.
For a sample that demonstrates a more robust command-line parsing technique that uses regular expressions, see Processing Command Line Arguments Sample.
XBAPs cannot retrieve and process command-line arguments because they are launched using ClickOnce deployment (see Deploying a WPF Application (WPF)). However, they can retrieve and process query string parameters from the URLs that are used to launch them. For an example, see URI Query String Parameters Sample.
Application Activation and Deactivation
Windows allows users to switch between applications. The most common way is to use the ALT+TAB key combination. An application can only be switched to if it has a visible Window that a user can select. The currently selected Window is the active window (also known as the foreground window) and is the Window that receives user input. The application with the active window is the active application (or foreground application). An application becomes the active application in the following circumstances:
You can detect when an application becomes active by handling the Application..::.Activated event.
Likewise, an application can become inactive in the following circumstances:
You can detect when an application becomes inactive by handling the Application..::.Deactivated event.
The following code shows how to handle the Activated and Deactivated events to determine whether an application is active.
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
StartupUri="MainWindow.xaml"
Activated="App_Activated"
Deactivated="App_Deactivated" />
using System; // EventArgs
using System.Windows; // Application
namespace SDKSample
{
public partial class App : Application
{
bool isApplicationActive;
void App_Activated(object sender, EventArgs e)
{
// Application activated
this.isApplicationActive = true;
}
void App_Deactivated(object sender, EventArgs e)
{
// Application deactivated
this.isApplicationActive = false;
}
}
}
A Window can also be activated and deactivated. See Window..::.Activated and Window..::.Deactivated for more information.
Application Shutdown
The life of an application ends when it is shut down, which can occur for the following reasons:
A user closes every Window.
A user closes the main Window.
A user ends the Windows session by logging off or shutting down.
An application-specific condition has been met.
To help you manage application shutdown, Application provides the Shutdown method, the ShutdownMode property, and the SessionEnding and Exit events.
Note: |
|---|
Shutdown can only be called from applications that have UIPermission. Standalone WPF applications always have this permission. However, XBAPs running in the Internet zone partial-trust security sandbox do not. |
Shutdown Mode
Most applications shut down either when all the windows are closed or when the main window is closed. Sometimes, however, other application-specific conditions may determine when an application shuts down. You can specify the conditions under which your application will shut down by setting ShutdownMode with one of the following ShutdownMode enumeration values:
The default value of ShutdownMode is OnLastWindowClose, which means that an application automatically shuts down when the last window in the application is closed by the user. However, if your application should be shut down when the main window is closed, WPF automatically does that if you set ShutdownMode to OnMainWindowClose. This is shown in the following example.
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
ShutdownMode="OnMainWindowClose" />
When you have application-specific shutdown conditions, you set ShutdownMode to OnExplicitShutdown. In this case, it is your responsibility to shut an application down by explicitly calling the Shutdown method; otherwise, your application will continue running even if all the windows are closed. Note that Shutdown is called implicitly when the ShutdownMode is either OnLastWindowClose or OnMainWindowClose.
Note: |
|---|
ShutdownMode can be set from an XBAP, but it is ignored; an XBAP is always shut down when it is navigated away from in a browser or when the browser that hosts the XBAP is closed. For more information, see Navigation Overview. |
Session Ending
The shutdown conditions that are described by the ShutdownMode property are specific to an application. In some cases, though, an application may shut down as a result of an external condition. The most common external condition occurs when a user ends the Windows session by the following actions:
Logging off
Shutting down
Restarting
Hibernating
To detect when a Windows session ends, you can handle the SessionEnding event, as illustrated in the following example.
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
StartupUri="MainWindow.xaml"
SessionEnding="App_SessionEnding" />
using System.Windows; // Application, SessionEndingCancelEventArgs, MessageBox, MessageBoxResult, MessageBoxButton
namespace SDKSample
{
public partial class App : Application
{
void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
{
// Ask the user if they want to allow the session to end
string msg = string.Format("{0}. End session?", e.ReasonSessionEnding);
MessageBoxResult result = MessageBox.Show(msg, "Session Ending", MessageBoxButton.YesNo);
// End session, if specified
if (result == MessageBoxResult.No)
{
e.Cancel = true;
}
}
}
}
In this example, the code inspects the ReasonSessionEnding property to determine how the Windows session is ending. It uses this value to display a confirmation message to the user. If the user does not want the session to end, the code sets Cancel to true to prevent the Windows session from ending.
Exit
When an application shuts down, it may need to perform some final processing, such as persisting application state. For these situations, you can handle the Exit event.
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
StartupUri="MainWindow.xaml"
Startup="App_Startup"
Exit="App_Exit">
...
</Application>
using System.Windows; // Application, StartupEventArgs
using System.IO; // StreamReader, FileMode
using System.IO.IsolatedStorage; // IsolatedStorageFile, IsolatedStorageFileStream
namespace SDKSample
{
public partial class App : Application
{
string filename = "App.txt";
...
private void App_Exit(object sender, ExitEventArgs e)
{
// Persist application-scope property to isolated storage
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForDomain();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, FileMode.Create, storage))
using (StreamWriter writer = new StreamWriter(stream))
{
// Persist each application-scope property individually
foreach (string key in this.Properties.Keys)
{
writer.WriteLine("{0},{1}", key, this.Properties[key]);
}
}
}
}
}
For the complete example, see How to: Persist and Restore Application-Scope Properties Across Application Sessions.
Exit can be handled by both standalone applications and XBAPs. For XBAPs, Exit is raised when in the following circumstances:
An XBAP is navigated away from.
In Internet Explorer 7, when the tab that is hosting the XBAP is closed.
When the browser is closed.
Exit Code
Applications are mostly launched by the operating system in response to a user request. However, an application can be launched by another application to perform some specific task. When the launched application shuts down, the launching application may want to know the condition under which the launched application shut down. In these situations, Windows allows applications to return an application exit code on shutdown. By default, WPF applications return an exit code value of 0.
Note: |
|---|
When you debug from Visual Studio, the application exit code is displayed in the Output window when the application shuts down, in a message that looks like the following:
The program '[5340] AWPFApp.vshost.exe: Managed' has exited with code 0 (0x0).
You open the Output window by clicking Output on the View menu. |
To change the exit code, you can call the Shutdown(Int32) overload, which accepts an integer argument to be the exit code:
// Shutdown and return a non-default exit code
Application.Current.Shutdown(-1);
You can detect the value of the exit code, and change it, by handling the Exit event. The Exit event handler is passed an ExitEventArgs which provides access to the exit code with the ApplicationExitCode property. For more information, see Exit.
Note: |
|---|
You can set the exit code in both standalone applications and XBAPs. However, the exit code value is ignored for XBAPs. |
Unhandled Exceptions
Sometimes an application may shut down under abnormal conditions, such as when an unanticipated exception is thrown. In this case, the application may not have the code to detect and process the exception. This type of exception is an unhandled exception; a notification similar to that shown in the following figure is displayed before the application is closed.
.png)
From the user experience perspective, it is better for an application to avoid this default behavior by doing some or all of the following:
Displaying user-friendly information.
Attempting to keep an application running.
Recording detailed, developer-friendly, exception information in the Windows event log.
Implementing this support depends on being able to detect unhandled exceptions, which is what the DispatcherUnhandledException event is raised for.
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
StartupUri="MainWindow.xaml"
DispatcherUnhandledException="App_DispatcherUnhandledException" />
using System.Windows; // Application
using System.Windows.Threading; // DispatcherUnhandledExceptionEventArgs
namespace SDKSample
{
public partial class App : Application
{
void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
// Process unhandled exception
...
// Prevent default unhandled exception processing
e.Handled = true;
}
}
}
The DispatcherUnhandledException event handler is passed a DispatcherUnhandledExceptionEventArgs parameter that contains contextual information regarding the unhandled exception, including the exception itself (DispatcherUnhandledExceptionEventArgs..::.Exception). You can use this information to determine how to handle the exception.
When you handle DispatcherUnhandledException, you should set the DispatcherUnhandledExceptionEventArgs..::.Handled property to true; otherwise, WPF still considers the exception to be unhandled and reverts to the default behavior described earlier. If an unhandled exception is raised and either the DispatcherUnhandledException event is not handled, or the event is handled and Handled is set to false, the application shuts down immediately. Furthermore, no other Application events are raised. Consequently, you need to handle DispatcherUnhandledException if your application has code that must run before the application shuts down.
Although an application may shut down as a result of an unhandled exception, an application usually shuts down in response to a user request, as discussed in the next section.
Application Lifetime Events
Standalone applications and XBAPs don't have exactly the same lifetimes. The following figure illustrates the key events in the lifetime of a standalone application and shows the sequence in which they are raised.
.png)
Likewise, the following figure illustrates the key events in the lifetime of an XBAP, and shows the sequence in which they are raised.
.png)