處理應用程式啟用Handle app activation

瞭解如何藉由覆寫 >onlaunched 方法來處理應用程式啟用。Learn how to handle app activation by overriding the Application.OnLaunched method.

覆寫啟動處理常式Override the launch handler

當應用程式啟動時,如果有任何原因,系統會傳送 CoreApplicationView 事件。When an app is activated, for any reason, the system sends the CoreApplicationView.Activated event. 如需啟用類型的清單,請參閱 ActivationKind 列舉。For a list of activation types, see the ActivationKind enumeration.

Windows.UI.Xaml.Application 類別定義了您可以覆寫來處理不同啟用類型的方法。The Windows.UI.Xaml.Application class defines methods you can override to handle the various activation types. 數種啟用類型有您可以覆寫的特定方法。Several of the activation types have a specific method that you can override. 如需其他啟用類型,請覆寫 OnActivated 方法。For the other activation types, override the OnActivated method.

定義應用程式的類別。Define the class for your application.

<Application
    x:Class="AppName.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

覆寫 OnLaunched 方法。Override the OnLaunched method. 不論使用者何時啟動 app 都會呼叫這個方法。This method is called whenever the user launches the app. LaunchActivatedEventArgs 參數包含 app 之前的狀態以及啟用引數。The LaunchActivatedEventArgs parameter contains the previous state of your app and the activation arguments.

注意

在 Windows 中,從 [開始] 磚或應用程式清單啟動暫停的應用程式不會呼叫這個方法。On Windows, launching a suspended app from Start tile or app list doesn't call this method.

using System;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;

namespace AppName
{
   public partial class App
   {
      async protected override void OnLaunched(LaunchActivatedEventArgs args)
      {
         EnsurePageCreatedAndActivate();
      }

      // Creates the MainPage if it isn't already created.  Also activates
      // the window so it takes foreground and input focus.
      private MainPage EnsurePageCreatedAndActivate()
      {
         if (Window.Current.Content == null)
         {
             Window.Current.Content = new MainPage();
         }

         Window.Current.Activate();
         return Window.Current.Content as MainPage;
      }
   }
}
Class App
   Protected Overrides Sub OnLaunched(args As LaunchActivatedEventArgs)
      Window.Current.Content = New MainPage()
      Window.Current.Activate()
   End Sub
End Class
...
#include "MainPage.h"
#include "winrt/Windows.ApplicationModel.Activation.h"
#include "winrt/Windows.UI.Xaml.h"
#include "winrt/Windows.UI.Xaml.Controls.h"
...
using namespace winrt;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;

struct App : AppT<App>
{
    App();

    /// <summary>
    /// Invoked when the application is launched normally by the end user.  Other entry points
    /// will be used such as when the application is launched to open a specific file.
    /// </summary>
    /// <param name="e">Details about the launch request and process.</param>
    void OnLaunched(LaunchActivatedEventArgs const& e)
    {
        Frame rootFrame{ nullptr };
        auto content = Window::Current().Content();
        if (content)
        {
            rootFrame = content.try_as<Frame>();
        }

        // Do not repeat app initialization when the Window already has content,
        // just ensure that the window is active
        if (rootFrame == nullptr)
        {
            // Create a Frame to act as the navigation context and associate it with
            // a SuspensionManager key
            rootFrame = Frame();

            rootFrame.NavigationFailed({ this, &App::OnNavigationFailed });

            if (e.PreviousExecutionState() == ApplicationExecutionState::Terminated)
            {
                // Restore the saved session state only when appropriate, scheduling the
                // final launch steps after the restore is complete
            }

            if (e.PrelaunchActivated() == false)
            {
                if (rootFrame.Content() == nullptr)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    rootFrame.Navigate(xaml_typename<BlankApp1::MainPage>(), box_value(e.Arguments()));
                }
                // Place the frame in the current Window
                Window::Current().Content(rootFrame);
                // Ensure the current window is active
                Window::Current().Activate();
            }
        }
        else
        {
            if (e.PrelaunchActivated() == false)
            {
                if (rootFrame.Content() == nullptr)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    rootFrame.Navigate(xaml_typename<BlankApp1::MainPage>(), box_value(e.Arguments()));
                }
                // Ensure the current window is active
                Window::Current().Activate();
            }
        }
    }
};
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml;
using namespace AppName;
void App::OnLaunched(LaunchActivatedEventArgs^ args)
{
   EnsurePageCreatedAndActivate();
}

// Creates the MainPage if it isn't already created.  Also activates
// the window so it takes foreground and input focus.
void App::EnsurePageCreatedAndActivate()
{
    if (_mainPage == nullptr)
    {
        // Save the MainPage for use if we get activated later
        _mainPage = ref new MainPage();
    }
    Window::Current->Content = _mainPage;
    Window::Current->Activate();
}

在 app 暫停然後終止時還原應用程式資料Restore application data if app was suspended then terminated

當使用者切換到已終止的 app 時,系統會傳送 Activated 事件,並將 Kind 設定成 Launch,以及將 PreviousExecutionState 設定成 TerminatedClosedByUserWhen the user switches to your terminated app, the system sends the Activated event, with Kind set to Launch and PreviousExecutionState set to Terminated or ClosedByUser. App 必須載入它已儲存的應用程式資料,並且重新整理已顯示的內容。The app should load its saved application data and refresh its displayed content.

async protected override void OnLaunched(LaunchActivatedEventArgs args)
{
   if (args.PreviousExecutionState == ApplicationExecutionState.Terminated ||
       args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
   {
      // TODO: Populate the UI with the previously saved application data
   }
   else
   {
      // TODO: Populate the UI with defaults
   }

   EnsurePageCreatedAndActivate();
}
Protected Overrides Sub OnLaunched(args As Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
   Dim restoreState As Boolean = False

   Select Case args.PreviousExecutionState
      Case ApplicationExecutionState.Terminated
         ' TODO: Populate the UI with the previously saved application data
         restoreState = True
      Case ApplicationExecutionState.ClosedByUser
         ' TODO: Populate the UI with the previously saved application data
         restoreState = True
      Case Else
         ' TODO: Populate the UI with defaults
   End Select

   Window.Current.Content = New MainPage(restoreState)
   Window.Current.Activate()
End Sub
void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs const& e)
{
    if (e.PreviousExecutionState() == ApplicationExecutionState::Terminated ||
        e.PreviousExecutionState() == ApplicationExecutionState::ClosedByUser)
    {
        // Populate the UI with the previously saved application data.
    }
    else
    {
        // Populate the UI with defaults.
    }
    ...
}
void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args)
{
   if (args->PreviousExecutionState == ApplicationExecutionState::Terminated ||
       args->PreviousExecutionState == ApplicationExecutionState::ClosedByUser)
   {
      // TODO: Populate the UI with the previously saved application data
   }
   else
   {
      // TODO: Populate the UI with defaults
   }

   EnsurePageCreatedAndActivate();
}

如果 PreviousExecutionState 的值是 NotRunning,app 將無法成功儲存它的應用程式資料,而且 app 必須從頭開始,如同它剛被初始啟動一般。If the value of PreviousExecutionState is NotRunning, the app failed to save its application data successfully and the app should start over as if it were being initially launched.

備註Remarks

注意

如果目前的視窗中已有設定的內容,App 便可以略過初始化程序。Apps can skip initialization if there is already content set on the current window. 您可以檢查 LaunchActivatedEventArgs TileId 屬性,以判斷應用程式是從主要或次要磚啟動,並根據該資訊來決定您是否應該提出全新或繼續的應用程式體驗。You can check the LaunchActivatedEventArgs.TileId property to determine whether the app was launched from a primary or a secondary tile and, based on that information, decide whether you should present a fresh or resume app experience.

重要 APIImportant APIs