Application Application Application Class

Definition

Encapsulates the app and its available services.

public : class Application : IApplication, IApplication2, IApplication3, IApplicationOverrides, IApplicationOverrides2
public class Application : IApplication, IApplication2, IApplication3, IApplicationOverrides, IApplicationOverrides2
Public Class Application Implements IApplication, IApplication2, IApplication3, IApplicationOverrides, IApplicationOverrides2
<Application />
 
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

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.

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 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 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 Application.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

Application() Application() Application()

Initializes a new instance of the Application class.

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

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.

Properties

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 Application
Value
Application Application Application

The Application object for the current application.

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

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 DebugSettings
Value
DebugSettings DebugSettings DebugSettings

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

Remarks

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

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 FocusVisualKind
Value
FocusVisualKind FocusVisualKind FocusVisualKind

The type of visual feedback used to indicate the UI element with focus. The default value depends on the operating system.

Windows 10, version 1607 and later HighVisibility

All previous versions DottedLine

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

Remarks

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

HighContrastAdjustment HighContrastAdjustment HighContrastAdjustment

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 ApplicationHighContrastAdjustment
Value
ApplicationHighContrastAdjustment ApplicationHighContrastAdjustment ApplicationHighContrastAdjustment

A value of the enumeration that indicates whether the framework automatically adjusts visual properties when high contrast themes are enabled. The default is Auto.

Additional features and requirements
Device family
Windows 10 Creators Update (introduced v10.0.15063.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v4)

Remarks

The value of this property affects all UIElement instances where the UIElement's HighContrastAdjustment has not been explicitly set. Setting it to None provides an easy way to disable the framework's automatic adjustments across all its windows and elements.

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 ApplicationTheme
<application RequestedTheme="applicationThemeMemberName" .../>
Value
ApplicationTheme ApplicationTheme ApplicationTheme

A value of the enumeration. The initial value is the default theme set by the user in Windows settings.

Remarks

There are two built in themes: "Light" and "Dark". By default your app runs using the theme set by the user in Windows settings (Settings > Personalization > Colors > Choose your default app mode). You can set the app's RequestedTheme property to override the user default and 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.

You can change specific theme values at run-time after Application.RequestedTheme is applied, if you use the FrameworkElement.RequestedTheme property and sets values on specific elements in the UI.

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.

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. This file is available in the (Program Files)\Windows Kits\10\DesignTime\CommonConfiguration\Neutral\UAP<SDK version>\Generic folder from a Windows Software Development Kit (SDK) installation.

Notes for Windows 8

(This section applies only to apps for Windows 8, not UWP apps for Windows 10.)

By default your app runs using the "Dark" theme (in the themeresources.xaml file, the key name for the "Dark" resources is "Default").

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

See Also

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 ApplicationRequiresPointerMode
Value
ApplicationRequiresPointerMode ApplicationRequiresPointerMode ApplicationRequiresPointerMode

The pointer emulation mode. The default is Auto (the default system experience for the input device).

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

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

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 ResourceDictionary
<Application>
  <Application.Resources>
    oneOrMoreResourceElements
  </Application.Resources>
</Application>
 
Value
ResourceDictionary ResourceDictionary ResourceDictionary

A ResourceDictionary object that contains zero or more application-scoped resources.

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 Application.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>

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.

See Also

Methods

Exit() Exit() Exit()

Shuts down the app.

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

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)

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(Platform::Object component, Uri resourceLocator)
public static void LoadComponent(Object component, Uri resourceLocator)
Public Static Function LoadComponent(component As Object, resourceLocator As Uri) As void
Parameters
component
Platform::Object Object Object

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

resourceLocator
Uri Uri Uri

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

Remarks

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

LoadComponent 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 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 XamlReader.Load 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 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.

See Also

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(Platform::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 void
Parameters
component
Platform::Object Object Object

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

resourceLocator
Uri Uri Uri

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

componentResourceLocation
ComponentResourceLocation ComponentResourceLocation ComponentResourceLocation

A value of the enumeration.

See Also

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 void
Parameters

Remarks

When a user launches your app normally (for example, by tapping the app tile), only the OnLaunched method is called. Override the OnActivated 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 IActivatedEventArgs.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 method:

For more info, see App lifecycle.

See Also

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 void
Parameters
Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

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 void
Parameters

Remarks

OnFileOpenPickerActivated 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, but defining overrides for other activation points such as OnCachedFileUpdaterActivated is up to your app code.

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

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

See Also

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 void
Parameters

Remarks

OnFileActivated 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, 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 Window.Activate in their implementations.

See Also

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 void
Parameters

Remarks

OnFileOpenPickerActivated 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 Window.Activate in their implementations.

See Also

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 void
Parameters

Remarks

OnFileSavePickerActivated 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 Window.Activate in their implementations.

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

See Also

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 void
Parameters

Remarks

Override the OnLaunched 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. Specific activation kinds sometimes have a specific override, also a virtual method on Application. For example, OnFileActivated 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. 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 Window.Activate in their implementations.

For example code of overrides of OnLaunched, 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 override is asynchronous, because some of the SuspensionManager API it calls is asynchronous. For more info, see Minimize startup time.

See Also

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 void
Parameters

Remarks

OnSearchActivated 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 Window.Activate in their implementations.

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

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

See Also

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 void
Parameters

Remarks

All Application overrides involved in an activation scenario should call Window.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.

See Also

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 void
Parameters

Remarks

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

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 void
Parameters
callback
ApplicationInitializationCallback ApplicationInitializationCallback ApplicationInitializationCallback

The callback that should be invoked during the initialization sequence.

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

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

public : event EnteredBackgroundEventHandler EnteredBackground<>
public event EnteredBackgroundEventHandler EnteredBackground<>
Public Event EnteredBackgroundEventHandler EnteredBackground( Of )
Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

LeavingBackground LeavingBackground LeavingBackground

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

public : event LeavingBackgroundEventHandler LeavingBackground<>
public event LeavingBackgroundEventHandler LeavingBackground<>
Public Event LeavingBackgroundEventHandler LeavingBackground( Of )
Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

Resuming Resuming Resuming

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

public : event EventHandler Resuming<Platform::Object>
public event EventHandler Resuming<object>
Public Event EventHandler Resuming( Of ( Of object ))

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 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.

See Also

Suspending Suspending Suspending

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

public : event SuspendingEventHandler Suspending<>
public event SuspendingEventHandler Suspending<>
Public Event SuspendingEventHandler Suspending( Of )

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 

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 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.

See Also

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 UnhandledException<>
public event UnhandledExceptionEventHandler UnhandledException<>
Public Event UnhandledExceptionEventHandler UnhandledException( Of )

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).

See Also

See Also