Application Application Application Class

Encapsulates the app and its available services.

Syntax

Declaration

public class Applicationpublic class ApplicationPublic Class Application
<Application />
 

Remarks

The Application class encapsulates an app and provides the following services:

  • app entry point, particularly for various activation contracts
  • app lifetime management
  • app-scoped resources
  • unhandled exception detection

The Application object is typically provided in the initial XAML for App.xaml. The default project templates in Visual Studio generate an App class that derives from Application and provides an entry point where you can add initialization code.

The App class associates itself with the corresponding XAML by calling the generated InitializeComponent method in its constructor. You can add additional initialization code to the App constructor, but you will typically only add code to associate handlers to Application events. For other initialization code, you should override one or more initialization methods such as OnLaunched(LaunchActivatedEventArgs).

The system handles app lifetime by suspending your app whenever the user switches to another app or to the desktop, and resuming your app whenever the user switches back to it. However, the system can also terminate your app while it is suspended in order to free up resources. You should handle the Suspending event to save your app state in case of termination, and override the OnLaunched(LaunchActivatedEventArgs) method to restore your app state. You should handle the Resuming event only if you need to refresh any displayed content that might have changed while the app is suspended. You do not need to restore other app state when the app resumes.

Because of its position in the application model, codegen, and activation sequence, Application has some restrictions on its XAML usage:

  • Other than the xmlns declarations and x:Class, no other attribute can appear on the Application root tag.
  • Don't attempt to change x:Class values that come from the project template App.xaml pages, there are additional dependencies on using that naming scheme that exist in the build actions.
  • Don't wire the Application event handlers in XAML. All event wiring should be done in code (usually in the constructor). Also, you generally use method overrides rather than event syntax for an event (for example, you override OnActivated(IActivatedEventArgs) to respond to that phase of the application life cycle.)
  • The only expected properties on an Application instance in XAML is the set of elements to populate the Resources property, using a XAML property element usage. For more info, see Resources. To provide general error handling for any exceptions that your app code doesn't catch, handle the UnhandledException event.
Note

The Application main file must be named App.xaml.

Constructors summary

Initializes a new instance of the Application class.

Properties summary

Gets the Application object for the current application.

Gets an object that declares how the app behaves when run in a debug environment.

Gets or sets the type of visual feedback that an app can use to indicate the UI element with focus.

This property is valid only for input devices that can generate key events, such as a keyboard or Xbox controller.

Prerelease. Gets or sets a value that indicates whether the framework automatically adjusts visual properties when high contrast themes are enabled.

Gets or sets a value that determines the light-dark preference for the overall theme of an app.

Gets or sets whether a UWP app supports mouse mode, which emulates pointer interaction experiences with non-pointer input devices such as an Xbox gamepad or remote control. (All nested elements inherit this behavior.)

Gets a collection of application-scoped resources, such as styles, templates, and brushes.

Methods summary

Shuts down the app.

Loads a XAML file that is located at the specified relative location, and converts it to an instance of the object that is specified by the root element of the XAML file.

Loads a XAML file that is located at the specified relative location, and converts it to an instance of the object that is specified by the root element of the XAML file.

Invoked when the application is activated by some means other than normal launching.

Invoked when the application is activated in the background.

Invoked when the application is activated due to an activation contract with ActivationKind as CachedFileUpdater.

Invoked when the application is activated through file-open.

Invoked when the application is activated through file-open dialog association.

Invoked when the application is activated through file-save dialog association.

Invoked when the application is launched. Override this method to perform application initialization and to display initial content in the associated Window.

Invoked when the application is activated through a search association.

Invoked when the application is activated through sharing association.

Invoked when the application creates a window.

Provides the entry point and requests initialization of the application. Use the callback to instantiate the Application class.

Events summary

Occurs when the app moves from the foreground to the background.

Occurs when the app moves from the background to the foreground.

Occurs when the application transitions from Suspended state to Running state.

Occurs when the application transitions to Suspended state from some other state.

Occurs when an exception can be handled by app code, as forwarded from a native-level Windows Runtime error. Apps can mark the occurrence as handled in event data.

Constructors

  • Application()
    Application()
    Application()
    Application()

    Initializes a new instance of the Application class.

    public Application()public New()Public Sub New()public Application()

    Remarks

    The Application object is typically provided in the initial XAML for App.xaml. The default project templates in Visual Studio generate an App class that derives from Application. This class associates itself with the XAML by calling the generated InitializeComponent method in its constructor. You can add additional initialization code to the App constructor, but you will typically only add code to associate handlers to Application events. For other initialization code, you should override one or more initialization methods such as OnLaunched(LaunchActivatedEventArgs).

Properties

  • Current
    Current
    Current
    Current

    Gets the Application object for the current application.

    public static Application Current { get; }public static Application Current { get; }Public Static ReadOnly Property Current As Applicationpublic static Application Current { get; }

    Property Value

    Remarks

    Application is a singleton that implements the static Current property to provide shared access to the Application instance for the current application. The singleton pattern ensures that state managed by Application, including shared resources and properties, is available from a single, shared location.

  • DebugSettings
    DebugSettings
    DebugSettings
    DebugSettings

    Gets an object that declares how the app behaves when run in a debug environment.

    public DebugSettings DebugSettings { get; }public DebugSettings DebugSettings { get; }Public ReadOnly Property DebugSettings As DebugSettingspublic DebugSettings DebugSettings { get; }

    Property Value

    Remarks

    To modify the app debug settings, get the DebugSettings object from this property and then change its properties as necessary.

  • FocusVisualKind
    FocusVisualKind
    FocusVisualKind
    FocusVisualKind

    Gets or sets the type of visual feedback that an app can use to indicate the UI element with focus.

    This property is valid only for input devices that can generate key events, such as a keyboard or Xbox controller.

    public FocusVisualKind FocusVisualKind { get; set; }public FocusVisualKind FocusVisualKind { get; set; }Public ReadWrite Property FocusVisualKind As FocusVisualKindpublic FocusVisualKind FocusVisualKind { get; set; }

    Property Value

    Remarks

    FocusVisualKind focus visuals are rendered with an outer (primary) and inner (secondary) border. For more info:

  • HighContrastAdjustment
    HighContrastAdjustment
    HighContrastAdjustment
    HighContrastAdjustment

    Prerelease. Gets or sets a value that indicates whether the framework automatically adjusts visual properties when high contrast themes are enabled.

    public ApplicationHighContrastAdjustment HighContrastAdjustment { get; set; }public ApplicationHighContrastAdjustment HighContrastAdjustment { get; set; }Public ReadWrite Property HighContrastAdjustment As ApplicationHighContrastAdjustmentpublic ApplicationHighContrastAdjustment HighContrastAdjustment { get; set; }

    Property Value

  • RequestedTheme
    RequestedTheme
    RequestedTheme
    RequestedTheme

    Gets or sets a value that determines the light-dark preference for the overall theme of an app.

    public ApplicationTheme RequestedTheme { get; set; }public ApplicationTheme RequestedTheme { get; set; }Public ReadWrite Property RequestedTheme As ApplicationThemepublic ApplicationTheme RequestedTheme { get; set; }
    <application RequestedTheme="applicationThemeMemberName" .../>
    

    Property Value

    Remarks

    There are two built in themes: "Light" and "Dark". By default your app runs using the "Dark" theme (in the themeresources.xaml file, the key name for the "Dark" resources is "Default"). You can set the app's RequestedTheme property to specify which theme is used.

    The theme can only be set when the app is started, not while it’s running. Attempting to set RequestedTheme while the app is running throws an exception (NotSupportedException for Microsoft .NET code). If you give the user an option to pick a theme that's part of app UI, you must save the setting in the app data and apply it when the app is restarted.

    There is also a "HighContrast" theme that uses system values, but apps and app code use a different technique for switching the app to high contrast. The RequestedTheme property is ignored if the user is running in high contrast mode. See High-contrast themes and XAML high contrast style sample.

    Although the app can't switch the themes at run-time, the user can (starting with Windows 8.1). For example, a user might enable a high-contrast theme while your app is running, by using the Alt+Shift+PrtScn key shortcut. If this happens, the XAML resource system will recalculate the resource values for any {ThemeResource} markup extension usage. Theme-appropriate resources such as colors and brushes then use values appropriate for the current theme, even though it wasn't the app that requested that theme originally.

    An app can change specific theme values at run-time after RequestedTheme is applied, if it uses the RequestedTheme property and sets values on specific elements in the UI.

    The resources that are theme-specific are typically defined in a separate resource dictionary in XAML. This resource dictionary comes from the ThemeDictionaries property of the primary ResourceDictionary that is used for control templates. The default system resource dictionary for theme-specific resources is named ThemeResources.xaml. Find this file under the path \include\winrt\xaml\design in your Windows Software Development Kit (SDK) for Windows 8 installation location.

    Note

    On Windows, setting RequestedTheme to ElementTheme will always result in "Dark" being the theme. On Windows Phone, using the ElementTheme value will result in a query for the system theme, as set by the user.

  • RequiresPointerMode
    RequiresPointerMode
    RequiresPointerMode
    RequiresPointerMode

    Gets or sets whether a UWP app supports mouse mode, which emulates pointer interaction experiences with non-pointer input devices such as an Xbox gamepad or remote control. (All nested elements inherit this behavior.)

    public ApplicationRequiresPointerMode RequiresPointerMode { get; set; }public ApplicationRequiresPointerMode RequiresPointerMode { get; set; }Public ReadWrite Property RequiresPointerMode As ApplicationRequiresPointerModepublic ApplicationRequiresPointerMode RequiresPointerMode { get; set; }

    Property Value

    Remarks

    For non-pointer input devices, focus is moved between controls through a variety of methods, such as the Tab and arrow keys on a keyboard, the directional pad (D-pad) on a remote, or thumb sticks on an Xbox controller. For some user experiences, such as maps and drawing surfaces, it is not possible or practical to use XY focus navigation. RequiresPointerMode enables an app to provide a more pointer-like interaction experience through a cursor that can be moved freely using the Xbox input devices.

    RequiresPointerMode is supported only on the Xbox device family, and only when using a game pad or remote control. The property is ignored otherwise.

    RequiresPointer sets mouse mode at the UI element level.

    For more info, see the Mouse mode section of Designing for Xbox and TV.

  • Resources
    Resources
    Resources
    Resources

    Gets a collection of application-scoped resources, such as styles, templates, and brushes.

    public ResourceDictionary Resources { get; set; }public ResourceDictionary Resources { get; set; }Public ReadWrite Property Resources As ResourceDictionarypublic ResourceDictionary Resources { get; set; }
    <Application>
      <Application.Resources>
        oneOrMoreResourceElements
      </Application.Resources>
    </Application>
     
    

    Property Value

    Remarks

    The resource dictionary model in the Windows Runtime supports many of the XAML resource concepts you may be familiar with if you have created applications using Windows Presentation Foundation (WPF) or Microsoft Silverlight. For more info, see ResourceDictionary and XAML resource references.

    The resources you define in the ResourceDictionary that fills the Application.Resources property element are available for retrieval from any page of your app. This is advantageous if many of your app's pages are all using the same resource. For example, if you have a SolidColorBrush resource that you're using for color schemes in your app's UI, and that color is used on most of your pages, it makes sense to declare that SolidColorBrush in the Application.Resources used for Application.Resources.

    When you add resources to Application.Resources, add them either before or after any existing ResourceDictionary.MergedResources. The rules of XAML don't allow you to put content on both sides of a property element tag. For more info, see XAML syntax guide.

    Resource loading optimization in Windows 8.1

    Starting with Windows 8.1, there's a resource loading optimization that's enabled by the app model and the Windows Runtime XAML parser. For Windows 8, the XAML parser loaded resources from app.xaml and created each of them as objects as part of startup. That wasn't very efficient if there were big dictionaries there. Also, those resources included the items that were needed by all three themes, and two of the three themes wouldn't even be active. Starting with Windows 8.1, the XAML parser only creates the resources when they're specifically requested. The request might come from other resources or from app or page XAML as each is loaded. This parser behavior minimizes the time it takes to read the app-level dictionary at startup time, and enables the first app page to load faster in most cases. Resources needed by other currently inactive themes are only loaded if that theme is chosen to become the active theme by the user. At that time, any resource where the {ThemeResource} markup extension was used for the request is recalculated based on the newly active theme.

    Windows 8 behavior

    Windows 8 didn't have the optimizations described above. The ResourceDictionary for Application.Resources had to finish parsing before any page other than the splash screen could load into the app's Window. Because of this you might see some differences in timing when you retarget your app for Windows 8.1. The app should be loading faster, however it may not be possible to isolate this improvement versus other changes you've made to your app code as part of retargeting. Some of the places where you might see evidence of timing changes due to optimized resource loading include when the constructors are called by the parser, for objects like Application objects, converters, or other custom classes. Apps that were compiled for Windows 8 but running on Windows 8.1 continue to use the Windows 8 behavior.

    For more info on performance and XAML resource factoring, see Optimize your XAML markup.

    Examples

    This example shows how to declare an app-specific resource (this one creates a common converter class instance that comes from starting templates). Then it adds an MergedDictionaries property element with ResourceDictionary elements within, each referencing a XAML file by URI as the Source.

    <Application.Resources>
        <ResourceDictionary>
          <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/> 
          <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="rd1.xaml" />
            <ResourceDictionary Source="rd2.xaml" />
          </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
      </Application.Resources>
    

Methods

  • Exit()
    Exit()
    Exit()
    Exit()

    Shuts down the app.

    public void Exit()public void Exit()Public Function Exit() As voidpublic void Exit()

    Remarks

    Use this method to provide UI that enables users to exit your app. Normally, however, you should not provide this UI because the system automatically manages app lifetime and terminates suspended apps as needed to free resources.

  • LoadComponent(Object, Uri)
    LoadComponent(Object, Uri)
    LoadComponent(Object, Uri)
    LoadComponent(Object, Uri)

    Loads a XAML file that is located at the specified relative location, and converts it to an instance of the object that is specified by the root element of the XAML file.

    public static void LoadComponent(Object component, Uri resourceLocator)public static void LoadComponent(Object component, Uri resourceLocator)Public Static Function LoadComponent(component As Object, resourceLocator As Uri) As voidpublic static void LoadComponent(Object component, Uri resourceLocator)

    Parameters

    • component
      System.Object
      System.Object
      System.Object

      An object of the same type as the root element of the XAML content to be loaded.

    • resourceLocator

      An object describing the Uniform Resource Identifier (URI) path to the resource to load.

    Remarks

    LoadComponent(Object, Uri) exists mainly for infrastructure. You can see LoadComponent(Object, Uri) as part of the generated InitializeComponent logic that integrates the partial classes of a XAML page and its code-behind.

    LoadComponent(Object, Uri) sometimes is cited in a call stack for an exception that is ultimately because your app is trying to parse bad XAML. In this case there's nothing that app code can do to change how LoadComponent(Object, Uri, ComponentResourceLocation) is used, and the way to fix the problem is to check your XAML source in an XML editor and fix it. What might be helpful from the stack trace message is confirming which XAML file is not loading. In scenarios where you have merged resources or other multiple XAML sources being combined, it's not always the obvious page-level XAML that is failing to parse.

    Most app scenarios that involve loading XAML content and producing an object tree should use Load(String) instead.

    Resource loading optimization in Windows 8.1

    Starting with Windows 8.1, there's a resource loading optimization that's enabled by the app model and the Windows Runtime XAML parser. LoadComponent(Object, Uri) is involved in this scenario because it's invoked internally to actually load any resource dictionary that comes from a XAML file, including those for MergedDictionaries. For Windows 8, the XAML parser loaded resources from app.xaml and created each of them as objects as part of startup. That wasn't very efficient if there were big dictionaries there. Also, those resources included the items that were needed by all three themes, and two of the three themes wouldn't even be active. Starting with Windows 8.1, the XAML parser only creates the resources when they're specifically requested. The request might come from other resources or from app or page XAML as each is loaded. This parser behavior minimizes the time it takes to read the app-level dictionary at startup time, and enables the first app page to load faster in most cases. Resources needed by other currently inactive themes are only loaded if that theme is chosen to become the active theme by the user. At that time, any resource where the {ThemeResource} markup extension was used for the request is recalculated based on the newly active theme.

    Windows 8 behavior

    Windows 8 didn't have the optimizations described above. The ResourceDictionary for Application.Resources had to finish parsing before any page other than the splash screen could load into the app's Window. Because of this you might see some differences in timing when you retarget your app for Windows 8.1. The app should be loading faster, however it may not be possible to isolate this improvement versus other changes you've made to your app code as part of retargeting. Some of the places where you might see evidence of timing changes due to optimized resource loading include when the constructors are called by the parser, for objects like Application objects, converters, or other custom classes. Apps that were compiled for Windows 8 but running on Windows 8.1 continue to use the Windows 8 behavior.

    For more info on performance and XAML resource factoring, see Optimize your XAML markup.

  • LoadComponent(Object, Uri, ComponentResourceLocation)
    LoadComponent(Object, Uri, ComponentResourceLocation)
    LoadComponent(Object, Uri, ComponentResourceLocation)
    LoadComponent(Object, Uri, ComponentResourceLocation)

    Loads a XAML file that is located at the specified relative location, and converts it to an instance of the object that is specified by the root element of the XAML file.

    public static void LoadComponent(Object component, Uri resourceLocator, ComponentResourceLocation componentResourceLocation)public static void LoadComponent(Object component, Uri resourceLocator, ComponentResourceLocation componentResourceLocation)Public Static Function LoadComponent(component As Object, resourceLocator As Uri, componentResourceLocation As ComponentResourceLocation) As voidpublic static void LoadComponent(Object component, Uri resourceLocator, ComponentResourceLocation componentResourceLocation)

    Parameters

  • OnActivated(IActivatedEventArgs)
    OnActivated(IActivatedEventArgs)
    OnActivated(IActivatedEventArgs)
    OnActivated(IActivatedEventArgs)

    Invoked when the application is activated by some means other than normal launching.

    protected virtual void OnActivated(IActivatedEventArgs args)protected virtual void OnActivated(IActivatedEventArgs args)Protected Overridable Function OnActivated(args As IActivatedEventArgs) As voidprotected virtual void OnActivated(IActivatedEventArgs args)

    Parameters

    Remarks

    When a user launches your app normally (for example, by tapping the app tile), only the OnLaunched(LaunchActivatedEventArgs) method is called. Override the OnActivated(IActivatedEventArgs) method to perform any general app initialization that should occur only when the app is not launched normally (for example, from another app through the Search contract). You can determine how the app was activated through the Kind property.

    For most kinds of activation, you can perform initialization specific to the activation type by overriding one of the following methods instead of the OnActivated(IActivatedEventArgs) method:

    For more info, see App lifecycle.

  • OnBackgroundActivated(BackgroundActivatedEventArgs)
    OnBackgroundActivated(BackgroundActivatedEventArgs)
    OnBackgroundActivated(BackgroundActivatedEventArgs)
    OnBackgroundActivated(BackgroundActivatedEventArgs)

    Invoked when the application is activated in the background.

    protected virtual void OnBackgroundActivated(BackgroundActivatedEventArgs args)protected virtual void OnBackgroundActivated(BackgroundActivatedEventArgs args)Protected Overridable Function OnBackgroundActivated(args As BackgroundActivatedEventArgs) As voidprotected virtual void OnBackgroundActivated(BackgroundActivatedEventArgs args)

    Parameters

  • OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs)
    OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs)
    OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs)
    OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs)

    Invoked when the application is activated due to an activation contract with ActivationKind as CachedFileUpdater.

    protected virtual void OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs args)protected virtual void OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs args)Protected Overridable Function OnCachedFileUpdaterActivated(args As CachedFileUpdaterActivatedEventArgs) As voidprotected virtual void OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs args)

    Parameters

    Remarks

    OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs) is a pre-defined activation point handler that is invoked for a core Activated event when the ActivationKind is CachedFileUpdater. The default template app.xaml code-behind files always include an override for OnLaunched(LaunchActivatedEventArgs), but defining overrides for other activation points such as OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs) is up to your app code.

    All Application overrides involved in an activation scenario should call Activate() in their implementations.

    For example code that overrides OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs), see File picker contracts sample.

  • OnFileActivated(FileActivatedEventArgs)
    OnFileActivated(FileActivatedEventArgs)
    OnFileActivated(FileActivatedEventArgs)
    OnFileActivated(FileActivatedEventArgs)

    Invoked when the application is activated through file-open.

    protected virtual void OnFileActivated(FileActivatedEventArgs args)protected virtual void OnFileActivated(FileActivatedEventArgs args)Protected Overridable Function OnFileActivated(args As FileActivatedEventArgs) As voidprotected virtual void OnFileActivated(FileActivatedEventArgs args)

    Parameters

    Remarks

    OnFileActivated(FileActivatedEventArgs) is a pre-defined activation point handler that is invoked for a core Activated event when the ActivationKind is File.

    An app can register to become the default handler for a certain file type. You should only register for a file type if you expect to handle all file launches for that type of file. In addition to overriding OnFileActivated(FileActivatedEventArgs), your app must also specify an extension point in the package manifest. For more info, see How to handle file activation.

    All Application overrides involved in an activation scenario should call Activate() in their implementations.

  • OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs)
    OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs)
    OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs)
    OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs)

    Invoked when the application is activated through file-open dialog association.

    protected virtual void OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs args)protected virtual void OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs args)Protected Overridable Function OnFileOpenPickerActivated(args As FileOpenPickerActivatedEventArgs) As voidprotected virtual void OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs args)

    Parameters

    Remarks

    OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs) is a pre-defined activation point handler that is invoked for a core Activated event when the ActivationKind is FileOpenPicker.

    All Application overrides involved in an activation scenario should call Activate() in their implementations.

  • OnFileSavePickerActivated(FileSavePickerActivatedEventArgs)
    OnFileSavePickerActivated(FileSavePickerActivatedEventArgs)
    OnFileSavePickerActivated(FileSavePickerActivatedEventArgs)
    OnFileSavePickerActivated(FileSavePickerActivatedEventArgs)

    Invoked when the application is activated through file-save dialog association.

    protected virtual void OnFileSavePickerActivated(FileSavePickerActivatedEventArgs args)protected virtual void OnFileSavePickerActivated(FileSavePickerActivatedEventArgs args)Protected Overridable Function OnFileSavePickerActivated(args As FileSavePickerActivatedEventArgs) As voidprotected virtual void OnFileSavePickerActivated(FileSavePickerActivatedEventArgs args)

    Parameters

    Remarks

    OnFileSavePickerActivated(FileSavePickerActivatedEventArgs) is a pre-defined activation point handler that is invoked for a core Activated event when the ActivationKind is FileSavePicker. This occurs when the user saves a file through the file picker and selects the app as the location.

    All Application overrides involved in an activation scenario should call Activate() in their implementations.

    For example code that shows an OnFileSavePickerActivated(FileSavePickerActivatedEventArgs) override, see File picker contracts sample.

  • OnLaunched(LaunchActivatedEventArgs)
    OnLaunched(LaunchActivatedEventArgs)
    OnLaunched(LaunchActivatedEventArgs)
    OnLaunched(LaunchActivatedEventArgs)

    Invoked when the application is launched. Override this method to perform application initialization and to display initial content in the associated Window.

    protected virtual void OnLaunched(LaunchActivatedEventArgs args)protected virtual void OnLaunched(LaunchActivatedEventArgs args)Protected Overridable Function OnLaunched(args As LaunchActivatedEventArgs) As voidprotected virtual void OnLaunched(LaunchActivatedEventArgs args)

    Parameters

    Remarks

    Override the OnLaunched(LaunchActivatedEventArgs) method to perform any general app initialization that should occur only when the user launches your app normally (for example, by tapping the app tile). For info on other kinds of activation, see OnActivated(IActivatedEventArgs). Specific activation kinds sometimes have a specific override, also a virtual method on Application. For example, OnFileActivated(FileActivatedEventArgs) is invoked for any core Activated event on the Application if the ActivationKind is File.

    The starting project templates include a basic implementation for OnLaunched(LaunchActivatedEventArgs). The implementation sets the initial root visual for the application by setting Window.Current.Content to a new instance of the class defined by the project template's MainPage XAML/code-behind pair. All Application overrides involved in an activation scenario should call Activate() in their implementations.

    For example code of overrides of OnLaunched(LaunchActivatedEventArgs), create a new app project and examine the template-created code in the app.xaml code-behind.

    Note

    The app.xaml code-behind from some project templates reference API in a SuspensionManager helper class. In this case, the OnLaunched(LaunchActivatedEventArgs) override is asynchronous, because some of the SuspensionManager API it calls is asynchronous. For more info, see Minimize startup time.

  • OnSearchActivated(SearchActivatedEventArgs)
    OnSearchActivated(SearchActivatedEventArgs)
    OnSearchActivated(SearchActivatedEventArgs)
    OnSearchActivated(SearchActivatedEventArgs)

    Invoked when the application is activated through a search association.

    protected virtual void OnSearchActivated(SearchActivatedEventArgs args)protected virtual void OnSearchActivated(SearchActivatedEventArgs args)Protected Overridable Function OnSearchActivated(args As SearchActivatedEventArgs) As voidprotected virtual void OnSearchActivated(SearchActivatedEventArgs args)

    Parameters

    Remarks

    OnSearchActivated(SearchActivatedEventArgs) is a pre-defined activation point handler that is invoked for a core Activated event when the ActivationKind is Search.

    All Application overrides involved in an activation scenario should call Activate() in their implementations.

    The Search contract sample demonstrates how to respond to a ActivationKind activated event.

    Consider writing your OnSearchActivated(SearchActivatedEventArgs) handler as asynchronous. For more info, see Minimize startup time.

  • OnShareTargetActivated(ShareTargetActivatedEventArgs)
    OnShareTargetActivated(ShareTargetActivatedEventArgs)
    OnShareTargetActivated(ShareTargetActivatedEventArgs)
    OnShareTargetActivated(ShareTargetActivatedEventArgs)

    Invoked when the application is activated through sharing association.

    protected virtual void OnShareTargetActivated(ShareTargetActivatedEventArgs args)protected virtual void OnShareTargetActivated(ShareTargetActivatedEventArgs args)Protected Overridable Function OnShareTargetActivated(args As ShareTargetActivatedEventArgs) As voidprotected virtual void OnShareTargetActivated(ShareTargetActivatedEventArgs args)

    Parameters

    Remarks

    All Application overrides involved in an activation scenario should call Activate() in their implementations.

    For example code, see Share target activation sample.

    Notes for previous versions

    Windows 8.x If your app is running when it is activated as a Share target, the existing instance of your app is terminated and a new instance of your app is launched to handle the contract.

  • OnWindowCreated(WindowCreatedEventArgs)
    OnWindowCreated(WindowCreatedEventArgs)
    OnWindowCreated(WindowCreatedEventArgs)
    OnWindowCreated(WindowCreatedEventArgs)

    Invoked when the application creates a window.

    protected virtual void OnWindowCreated(WindowCreatedEventArgs args)protected virtual void OnWindowCreated(WindowCreatedEventArgs args)Protected Overridable Function OnWindowCreated(args As WindowCreatedEventArgs) As voidprotected virtual void OnWindowCreated(WindowCreatedEventArgs args)

    Parameters

    Remarks

    This method is called once for the creation of the main window, once for each hosted window, and once each time CreateNewView(IFrameworkViewSource) is called. You can override this method, for example, to access various panes by calling GetForCurrentView methods such as GetForCurrentView() and GetForCurrentView().

  • Start(ApplicationInitializationCallback)
    Start(ApplicationInitializationCallback)
    Start(ApplicationInitializationCallback)
    Start(ApplicationInitializationCallback)

    Provides the entry point and requests initialization of the application. Use the callback to instantiate the Application class.

    public static void Start(ApplicationInitializationCallback callback)public static void Start(ApplicationInitializationCallback callback)Public Static Function Start(callback As ApplicationInitializationCallback) As voidpublic static void Start(ApplicationInitializationCallback callback)

    Parameters

    Remarks

    Typically, you will not need to call this method directly. If you use Visual Studio to develop your apps, the build system will generate code that includes the necessary call for you.

Events

  • EnteredBackground
    EnteredBackground
    EnteredBackground
    EnteredBackground

    Occurs when the app moves from the foreground to the background.

    public event EnteredBackgroundEventHandler EnteredBackgroundpublic event EnteredBackgroundEventHandler EnteredBackgroundPublic Event EnteredBackgroundpublic event EnteredBackgroundEventHandler EnteredBackground
  • LeavingBackground
    LeavingBackground
    LeavingBackground
    LeavingBackground

    Occurs when the app moves from the background to the foreground.

    public event LeavingBackgroundEventHandler LeavingBackgroundpublic event LeavingBackgroundEventHandler LeavingBackgroundPublic Event LeavingBackgroundpublic event LeavingBackgroundEventHandler LeavingBackground
  • Resuming
    Resuming
    Resuming
    Resuming

    Occurs when the application transitions from Suspended state to Running state.

    public event EventHandler Resumingpublic event EventHandler ResumingPublic Event Resumingpublic event EventHandler Resuming

    Remarks

    The system suspends your app whenever the user switches to another app or to the desktop, and resumes your app whenever the user switches back to it. However, the system can also terminate your app while it is suspended in order to free up resources. Therefore, you should handle the Suspending event to save your app state.

    If your app is terminated, you can restore the app state in an OnLaunched(LaunchActivatedEventArgs) method override. If your app resumes before it is terminated, the system restores the app state automatically. You should handle the Resuming event only if you need to refresh any displayed content that might have changed while the app is suspended, such as news feeds or the user's location.

    Applications should avoid invoking code that puts a high load on the UI thread in response to Resuming. Doing so gives appearance to the user that the shell is being unresponsive, when in fact it is your application code that is the throttle point. Delegate operations to other threads if possible, or use a staged or virtualized approach for rebuilding views and UI whenever the application is resumed.

  • Suspending
    Suspending
    Suspending
    Suspending

    Occurs when the application transitions to Suspended state from some other state.

    public event SuspendingEventHandler Suspendingpublic event SuspendingEventHandler SuspendingPublic Event Suspendingpublic event SuspendingEventHandler Suspending

    Remarks

    The system suspends your app whenever the user switches to another app or to the desktop, and resumes your app whenever the user switches back to it. However, the system can also terminate your app while it is suspended in order to free up resources. Therefore, you should handle the Suspending event to perform the following operations:

    • Preserve user session state.
    • Release any exclusive locks on resources.
    • Reduce memory usage if possible. For example, serialize any data that is easy to reconstruct in object form upon reactivation.
    • Save app state. The Suspending event is the only indication your app will receive prior to termination (if it happens). Because of this, you should store enough session state (such as the current article being read or the current movie playback position) to recreate the exact same experience during activation. The guidance for content creation apps is to save a user’s work early and often but also commit one final save during Suspending. Saving data prior to suspension is useful because the Suspending event handler has only 5 seconds to complete its operation.

    If your app is terminated, you can restore the app state in an OnLaunched(LaunchActivatedEventArgs) method override. If your app resumes before it is terminated, the system restores the app state automatically. You should handle the Resuming event only if you need to refresh any displayed content that might have changed while the app is suspended, such as news feeds or the user's location.

    Examples

    This code example demonstrates a typical usage pattern for this event. This code is used by many of the XAML samples, for example the Input sample, as part of the code-behind for the app.xaml file. If you browse the XAML samples, you can find the source code for the SuspensionManager class API as referenced in this code.

    async protected void OnSuspending(object sender, SuspendingEventArgs args)
    {
        SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
        await SuspensionManager.SaveAsync();
        deferral.Complete();
    }
    
    Private Async Sub OnSuspending(sender As Object, args As SuspendingEventArgs) 
        Dim deferral As SuspendingDeferral = args.SuspendingOperation.GetDeferral 
        Await SuspensionManager.SaveAsync 
        deferral.Complete() 
    End Sub 
    
  • UnhandledException
    UnhandledException
    UnhandledException
    UnhandledException

    Occurs when an exception can be handled by app code, as forwarded from a native-level Windows Runtime error. Apps can mark the occurrence as handled in event data.

    public event UnhandledExceptionEventHandler UnhandledExceptionpublic event UnhandledExceptionEventHandler UnhandledExceptionPublic Event UnhandledExceptionpublic event UnhandledExceptionEventHandler UnhandledException

    Remarks

    The UnhandledException event is used to notify the app about exceptions encountered by the XAML framework or by the Windows Runtime in general that have not been handled by app code.

    For example, if the Windows Runtime invokes app code like an event handler, and the app code throws an exception and does not catch it, the exception will propagate back to the Windows Runtime. The Windows Runtime will then fire the UnhandledException event to notify the app of this exception.

    Handling exceptions in an UnhandledException is just one of many techniques that can be used both for debugging and for run-time exception handling and possible recovery. For more info about the full set of techniques you might use for debugging and error handling, see Exception handling for in C# or Visual Basic.

    Note that this event will only fire when there is no longer any possibility that app code can catch an exception. For example, imagine that an app event handler calls a Windows Runtime API that in turn invokes a callback. If the inner app code throws an exception and does not catch it, the exception will propagate through the Windows Runtime back to the outer layer of app code, which is given a chance to catch it. The UnhandledException event is fired only when there are no more opportunities for app code to catch an exception through normal propagation.

    It’s also possible for an exception to be thrown and never have any chance to be caught by app code. For example, if the XAML framework is performing layout and an exception is thrown, this exception won’t propagate through any app code. In this case, the UnhandledException event fires, and this will be the first time any app code is notified about the exception.

    Normally after the UnhandledException event is fired, the Windows Runtime terminates the app because the exception was unhandled. The app code has some control over this: if the UnhandledException event handler sets the Handled property of the event arguments to true, then in most cases the app will not be terminated. However, doing so routinely is not recommended for several reasons:

    • Typically the UnhandledException event handler doesn’t have enough information to know whether continuing on after an exception is safe. Parts of the application code or the Windows Runtime may be in an inconsistent state, which could result in subsequent failures if the app continues running its code.
    • The Windows Runtime considers exceptions encountered during certain operations as nonrecoverable, because the Windows Runtime itself will be in an inconsistent state following these exceptions. For such exceptions, even if the UnhandledException event handler sets Handled to true, the app will still be terminated.
    • Errors that happen during navigation could cause a state where there's nothing loaded as content and nothing to indicate to the user that the app is still running.
    • For more info on these points see Exception handling for in C# or Visual Basic.

    A notable limitation is that the UnhandledException event arguments don’t contain as much detail as the original exception as propagated from app code. Whenever possible, if the app requires specific processing of a certain exception, it’s always better to catch the exception as it propagates, because more detail will be available then. The UnhandledException event arguments expose an exception object through the Exception property. However, the type, message, and stack trace of this exception object are not guaranteed to match those of the original exception that was raised. The event arguments do expose a Message property. In most cases, this will contain the message of the originally raised exception.

    You can't wire handlers for UnhandledException in XAML (on the Application element in App.xaml). You must attach handlers for UnhandledException on the Application object in code, either in the constructor or in activation logic.

    For Windows 8.1 apps, exceptions from async method calls can propagate as an UnhandledException event. This includes your own async method implementations (activation handlers and so on).

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.ComposableAttribute
Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.ThreadingAttribute
Windows.Foundation.Metadata.WebHostHiddenAttribute

Details

Assembly

Windows.UI.Xaml.dll