Visão Geral do Gerenciamento de Aplicativo
Este tópico fornece uma visão geral sobre o Windows Presentation Foundation (WPF) services para criar e gerenciar aplicativos. The kernel of a WPF application is the Application class, which supports a variety of the core application services. This topic provides an introduction to the most important of these services.
Este tópico contém as seguintes seções.
- The Application Class
- The Application Definition
- Getting the Current Application
- Application Lifetime
- Other Application Services
- Tópicos relacionados
The Application Class
An application consists of many application-specific elements, including user interface (UI), business logic, data access logic, controls, and data. These elements typically differ from one application to the next. However, all applications tend to share a common set of functionality that facilitates application implementation and management. Em WPF, essa funcionalidade comum de escopo do aplicativo é encapsulada pela Application classe, que fornece os seguintes serviços:
Creating and managing common application infrastructure.
Tracking and interacting with application lifetime.
Retrieving and processing command-line parameters.
Sharing application-scope properties and resources.
Detecting and responding to unhandled exceptions.
Returning exit codes.
Managing windows in standalone applications (see Visão geral do WPF do Windows).
Tracking and managing navigation (see Visão geral de navegação).
To use these services in your application, you need to use the Application class to implement an application definition.
The Application Definition
A WPF definição de aplicativo é uma classe que deriva de Application e está configurado com um especial Microsoft build engine (MSBuild) configuração.
Implementing an Application Definition
A typical WPF application definition is implemented using both markup and code-behind. This allows you to use markup to declaratively set application properties, resources, and register events, while handling events and implementing application-specific behavior in code-behind.
The following example shows how to implement an application definition using both markup and code-behind:
<Application
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App" />
Imports Microsoft.VisualBasic
Imports System.Windows ' Application
Namespace SDKSample
Partial Public Class App
Inherits Application
End Class
End Namespace
using System.Windows; // Application
namespace SDKSample
{
public partial class App : Application { }
}
To allow a markup file and code-behind file to work together, the following needs to happen:
In markup, the Application element must include the x:Class attribute. Quando o aplicativo é criado, a existência de x:Class na marcação do arquivo faz com que MSBuild para criar um partial classe que deriva de Application e tem o nome especificado pelo x:Class atributo. This requires the addition of an XML namespace declaration for the XAML schema (xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml").
In code-behind, the class must be a partial class with the same name that is specified by the x:Class attribute in markup and must derive from Application. This allows the code-behind file to be associated with the partial class that is generated for the markup file when the application is built (see Building a WPF Application (WPF)).
Observação
When you create a new WPF Application project or WPF Browser Application project using Microsoft Visual Studio, an application definition is included by default and is defined using both markup and code-behind.
This code is the minimum that is required to implement an application definition. No entanto, adicional MSBuild configuração precisa ser feita para a definição de aplicativo antes de construir e executar o aplicativo.
Configuring the Application Definition for MSBuild
Standalone applications and XAML browser applications (XBAPs) require the implementation of a certain level of infrastructure before they can run. The most important part of this infrastructure is the entry point. When an application is launched by a user, the operating system calls the entry point, which is a well-known function for starting applications.
Traditionally, developers have needed to write some or all of this code for themselves, depending on the technology. No entanto, WPF gera este código quando o arquivo de marcação da definição do aplicativo é configurado como um MSBuild ApplicationDefinition item, conforme mostrado no seguinte MSBuild o arquivo de projeto:
<Project
DefaultTargets="Build"
xmlns="https://schemas.microsoft.com/developer/msbuild/2003">
...
<ApplicationDefinition Include="App.xaml" />
<Compile Include="App.xaml.cs" />
...
</Project>
Porque o arquivo de code-behind contém código, ele é marcado como um MSBuild Compile item, como é normal.
The application of these MSBuild configurations to the markup and code-behind files of an application definition causes MSBuild to generate code like the following:
Imports Microsoft.VisualBasic
Imports System ' STAThread
Imports System.Windows ' Application
Namespace SDKSample
Public Class App
Inherits Application
Public Sub New()
End Sub
<STAThread>
Public Shared Sub Main()
' Create new instance of application subclass
Dim app As New App()
' Code to register events and set properties that were
' defined in XAML in the application definition
app.InitializeComponent()
' Start running the application
app.Run()
End Sub
Public Sub InitializeComponent()
...
End Sub
End Class
End Namespace
using System; // STAThread
using System.Windows; // Application
namespace SDKSample
{
public class App : Application
{
public App() { }
[STAThread]
public static void Main()
{
// Create new instance of application subclass
App app = new App();
// Code to register events and set properties that were
// defined in XAML in the application definition
app.InitializeComponent();
// Start running the application
app.Run();
}
public void InitializeComponent()
{
...
}
}
}
The resulting code augments your application definition with additional infrastructure code, which includes the entry-point method Main. O STAThreadAttribute atributo é aplicado para o Main método para indicar que principal UI thread para o WPF aplicativo é um segmento STA, que é necessário para WPF aplicativos. Quando chamado, Main cria uma nova instância de App antes de chamar o InitializeComponent método para registrar os eventos e definir as propriedades que são implementadas na marcação. Porque InitializeComponent é gerado para você, você não precisa chamar explicitamente InitializeComponent uma definição de aplicativo, como em Page e Window implementações. Finalmente, o Run método é chamado para iniciar o aplicativo.
Getting the Current Application
Because the services of the Application class are shared across an application, there can be only one instance of the Application class per AppDomain. To enforce this, the Application class is implemented as a singleton class (see Implementing Singleton in C#), which creates a single instance of itself and provides shared access to it with the static Current property.
The following code shows how to acquire a reference to the Application object for the current AppDomain.
' Get current application
Dim current As Application = App.Current
// Get current application
Application current = App.Current;
Current returns a reference to an instance of the Application class. If you want a reference to your Application derived class you must cast the value of the Current property, as shown in the following example.
' Get strongly-typed current application
Dim appCurrent As App = CType(App.Current, App)
// Get strongly-typed current application
App app = (App)App.Current;
You can inspect the value of Current at any point in the lifetime of an Application object. However, you should be careful. After the Application class is instantiated, there is a period during which the state of the Application object is inconsistent. During this period, Application is performing the various initialization tasks that are required by your code to run, including establishing application infrastructure, setting properties, and registering events. If you try to use the Application object during this period, your code may have unexpected results, particularly if it depends on the various Application properties being set.
When Application completes its initialization work, its lifetime truly begins.
Application Lifetime
O tempo de vida de um WPF aplicativo é marcado por vários eventos que são gerados pelo Application para que você saiba quando seu aplicativo foi iniciado, foi ativado e desativado e tem sido shut down.
Esta seção contém as seguintes subseções.
- Splash Screen
- Starting an Application
- Showing a User Interface
- Processing Command-Line Arguments
- Application Activation and Deactivation
- Application Shutdown
- Unhandled Exceptions
- Application Lifetime Events
Splash Screen
A partir de .NET Framework 3.5 SP1, você pode especificar uma imagem a ser usado em uma janela de inicialização, ou tela de abertura. O SplashScreen classe torna fácil exibir uma janela de inicialização, enquanto o aplicativo está carregando. O SplashScreen janela é criada e mostrada antes de Run é chamado. Para obter mais informações, consulte Tempo de inicialização do aplicativo e Como: Adicionar uma tela de abertura para um aplicativo WPF.
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:
Imports Microsoft.VisualBasic
Imports System.Windows ' Application, StartupEventArgs, WindowState
Namespace SDKSample
Partial Public Class App
Inherits Application
Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs)
' Application is running
...
End Sub
End Class
End Namespace
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
Independente da maioria dos Windows aplicativos abrem um Window quando eles começarem em execução. The Startup event handler is one location from which you can do this, as demonstrated by the following code.
<Application
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
Startup="App_Startup" />
Imports Microsoft.VisualBasic
Imports System.Windows ' Application, StartupEventArgs
Namespace SDKSample
Partial Public Class App
Inherits Application
Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs)
' Open a window
Dim window As New MainWindow()
window.Show()
End Sub
End Class
End Namespace
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();
}
}
}
Observação
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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
Startup="App_Startup" />
Imports System ' Uri, UriKind, EventArgs, Console
Imports System.Windows ' Application, StartupEventArgs
Imports System.Windows.Navigation ' NavigationWindow
Namespace SDKSample
Partial Public Class App
Inherits Application
Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs)
CType(Me.MainWindow, NavigationWindow).Navigate(New Uri("HomePage.xaml", UriKind.Relative))
End Sub
End Class
End Namespace
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="https://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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
StartupUri="HomePage.xaml" />
This markup has the same effect as the previous code for opening a window.
Observação
For more information on navigation, see Visão geral de navegação.
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. Em ambos os casos, os argumentos de linha de comando podem ser passados para o aplicativo. O exemplo a seguir mostra um aplicativo que é iniciado com um único argumento de linha de comando "/ 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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
Startup="App_Startup" />
Imports Microsoft.VisualBasic
Imports System.Windows ' Application, StartupEventArgs, WindowState
Namespace SDKSample
Partial Public Class App
Inherits Application
Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs)
' Application is running
' Process command line args
Dim startMinimized As Boolean = False
Dim i As Integer = 0
Do While i <> e.Args.Length
If e.Args(i) = "/StartMinimized" Then
startMinimized = True
End If
i += 1
Loop
' Create main application window, starting minimized if specified
Dim mainWindow As New MainWindow()
If startMinimized Then
mainWindow.WindowState = WindowState.Minimized
End If
mainWindow.Show()
End Sub
End Class
End Namespace
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.
XBAPsnão é possível recuperar e processar os argumentos de linha de comando, porque eles são iniciados usando ClickOnce implantação (consulte Implantar um aplicativo WPF (WPF)). However, they can retrieve and process query string parameters from the URLs that are used to launch them.
Application Activation and Deactivation
Windowspermite aos usuários alternar entre aplicativos. A maneira mais comum é usar a combinação de teclas ALT + TAB. An application can only be switched to if it has a visible Window that a user can select. Selecionado no momento Window é o janela ativa (também conhecido como o a janela de primeiro plano) e é o Window que recebe entrada do usuário. O aplicativo com a janela ativa é a aplicativo ativo (ou aplicativo de primeiro plano). Um aplicativo se torna o aplicativo ativo nas seguintes circunstâncias:
It is launched and shows a Window.
A user switches from another application by selecting a Window in the application.
You can detect when an application becomes active by handling the Application.Activated event.
Likewise, an application can become inactive in the following circumstances:
A user switches to another application from the current one.
When the application shuts down.
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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
StartupUri="MainWindow.xaml"
Activated="App_Activated"
Deactivated="App_Deactivated" />
Imports Microsoft.VisualBasic
Imports System ' EventArgs
Imports System.Windows ' Application
Namespace SDKSample
Partial Public Class App
Inherits Application
Private isApplicationActive As Boolean
Private Sub App_Activated(ByVal sender As Object, ByVal e As EventArgs)
' Application activated
Me.isApplicationActive = True
End Sub
Private Sub App_Deactivated(ByVal sender As Object, ByVal e As EventArgs)
' Application deactivated
Me.isApplicationActive = False
End Sub
End Class
End Namespace
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.
Observação
Neither Application.Activated nor Application.Deactivated is raised for XBAPs.
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.
Observação
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. No entanto, se seu aplicativo deve ser desligado quando a janela principal é fechada, WPF faz isso automaticamente se você definir ShutdownMode para OnMainWindowClose. This is shown in the following example.
<Application
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://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.
Observação
ShutdownModepode ser definida a partir de um XBAP, mas ele é ignorado; um XBAP é sempre desligado quando sair de em um navegador ou quando o navegador que hospeda o XBAP está fechado.For more information, see Visão geral de navegação.
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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
StartupUri="MainWindow.xaml"
SessionEnding="App_SessionEnding" />
Imports Microsoft.VisualBasic
Imports System.Windows ' Application, SessionEndingCancelEventArgs, MessageBox, MessageBoxResult, MessageBoxButton
Namespace SDKSample
Partial Public Class App
Inherits Application
Private Sub App_SessionEnding(ByVal sender As Object, ByVal e As SessionEndingCancelEventArgs)
' Ask the user if they want to allow the session to end
Dim msg As String = String.Format("{0}. End session?", e.ReasonSessionEnding)
Dim result As MessageBoxResult = MessageBox.Show(msg, "Session Ending", MessageBoxButton.YesNo)
' End session, if specified
If result = MessageBoxResult.No Then
e.Cancel = True
End If
End Sub
End Class
End Namespace
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;
}
}
}
}
Neste exemplo, o código inspeciona o ReasonSessionEnding propriedade para determinar como o Windows a sessão está terminando. It uses this value to display a confirmation message to the user. Se o usuário não deseja que a sessão para finalizar, o código define Cancel para true para impedir que o Windows sessão de terminação.
Observação
SessionEnding is not raised for XBAPs.
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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
StartupUri="MainWindow.xaml"
Startup="App_Startup"
Exit="App_Exit">
...
</Application>
Imports System.IO ' StreamReader, FileMode
Imports System.IO.IsolatedStorage ' IsolatedStorageFile, IsolatedStorageFileStream
Namespace SDKSample
Partial Public Class App
Inherits Application
Private filename As String = "App.txt"
...
Private Sub App_Exit(ByVal sender As Object, ByVal e As ExitEventArgs)
' Persist application-scope property to isolated storage
Dim storage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForDomain()
Using stream As New IsolatedStorageFileStream(filename, FileMode.Create, storage)
Using writer As New StreamWriter(stream)
' Persist each application-scope property individually
For Each key As String In Me.Properties.Keys
writer.WriteLine("{0},{1}", key, Me.Properties(key))
Next key
End Using
End Using
End Sub
End Class
End Namespace
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 Como: Persistir e Restaurar propriedades de escopo de aplicativos em sessões de aplicativos.
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. Nessas situações, Windows permite que os aplicativos retornar um código de saída de aplicativos no desligamento. By default, WPF applications return an exit code value of 0.
Observação
Quando você depurar a partir de Visual Studio, o código de saída do aplicativo é exibido na saída janela quando o aplicativo é desligado, em uma mensagem que se parece com o seguinte:
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)
// 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.
Observação
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.
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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.App"
StartupUri="MainWindow.xaml"
DispatcherUnhandledException="App_DispatcherUnhandledException" />
Imports Microsoft.VisualBasic
Imports System.Windows ' Application
Imports System.Windows.Threading ' DispatcherUnhandledExceptionEventArgs
Namespace SDKSample
Partial Public Class App
Inherits Application
Private Sub App_DispatcherUnhandledException(ByVal sender As Object, ByVal e As DispatcherUnhandledExceptionEventArgs)
' Process unhandled exception
...
' Prevent default unhandled exception processing
e.Handled = True
End Sub
End Class
End Namespace
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
Aplicativos autônomos e XBAPs não têm exatamente o mesmo tempo de vida. A figura a seguir ilustra os principais eventos em tempo de vida de um aplicativo autônomo e mostra a seqüência na qual eles são disparados.
Likewise, the following figure illustrates the key events in the lifetime of an XBAP, and shows the sequence in which they are raised.
Other Application Services
In addition to managing the lifetime of an application, Application provides services that include the following:
Shared application-scope properties.
Shared application-scope resources.
Application resource, content, and site-of-origin data files.
Window management.
Navigation management.
Shared Application-Scope Properties
Application provides the Properties property to expose state that can be shared across the breadth of an application. The following provides an example of using Properties:
' Set an application-scope property with a custom type
Dim customType As New CustomType()
Application.Current.Properties("CustomType") = customType
...
' Get an application-scope property
' NOTE: Need to convert since Application.Properties is a dictionary of System.Object
Dim customType As CustomType = CType(Application.Current.Properties("CustomType"), CustomType)
// Set an application-scope property with a custom type
CustomType customType = new CustomType();
Application.Current.Properties["CustomType"] = customType;
...
// Get an application-scope property
// NOTE: Need to convert since Application.Properties is a dictionary of System.Object
CustomType customType = (CustomType)Application.Current.Properties["CustomType"];
See the following for more information:
Shared Application-Scope Resources
Application provides the Resources property to allow developers to share UI resources across an application. The following provides an example of using Resources:
' Set an application-scope resource
Application.Current.Resources("ApplicationScopeResource") = Brushes.White
...
' Get an application-scope resource
Dim whiteBrush As Brush = CType(Application.Current.Resources("ApplicationScopeResource"), Brush)
// Set an application-scope resource
Application.Current.Resources["ApplicationScopeResource"] = Brushes.White;
...
// Get an application-scope resource
Brush whiteBrush = (Brush)Application.Current.Resources["ApplicationScopeResource"];
See the following for more information:
Application Resource, Content, and Site-Of-Origin Data Files
WPF applications can manage several types of non-code data files, including resource files, content files, and site-of-origin files. The following helper methods can be used to load these types of data files:
Window Management
Application and Window have a close relationship. Como você viu o tempo de vida de um aplicativo pode depender do tempo de vida do seus windows, conforme especificado pelo ShutdownMode propriedade. Applicationqual janela é designada a janela principal do aplicativo de registros (Application.MainWindow) e mantém uma lista do windows atualmente instanciados (Application.Windows).
For more information, see Visão geral do WPF do Windows.
Navigation Management
For standalone applications with navigation (using NavigationWindow and Frame) or XBAPs, Application detects any navigation within an application and raises the following events as appropriate:
Furthermore, Application provides the ability for applications of any type to create, persist, and retrieve cookies, using GetCookie and SetCookie
For more information, see Visão geral de navegação.
Consulte também
Referência
Conceitos
Recursos, conteúdo e arquivos de dados de aplicativos WPF