Partager via


Notifications d’application de UWP vers la migration WinUI 3

La seule différence lors de la migration du code de notification d’application de UWP vers WinUI 3 consiste à gérer l’activation des notifications. L’envoi et la gestion des notifications d’application restent exactement identiques.

Remarque

Le terme « notification toast » est remplacé par « notification d’application ». Ces termes font tous deux référence à la même fonctionnalité de Windows, mais au fil du temps, nous allons effectuer une phase d’utilisation de la « notification toast » dans la documentation.

Remarque

Certaines informations portent sur la préversion du produit, qui est susceptible d’être en grande partie modifié avant sa commercialisation. Microsoft n’offre aucune garantie, expresse ou implicite, concernant les informations fournies ici.

Différences d’activation

Catégorie UWP WinUI 3
Point d’entrée d’activation de premier plan OnActivated la méthode à l’intérieur App.xaml.cs est appelée OnLaunched la méthode à l’intérieur App.xaml.cs est appelée.
Point d’entrée d’activation en arrière-plan Géré séparément en tant que tâche en arrière-plan Identique à l’activation au premier plan. OnLaunched la méthode à l’intérieur App.xaml.cs est appelée. Utilisez GetActivatedEventArgs pour déterminer si l’application doit démarrer entièrement ou simplement gérer la tâche et quitter.
Activation de la fenêtre Votre fenêtre est automatiquement mise au premier plan lorsque l’activation au premier plan se produit Vous devez mettre votre fenêtre au premier plan si vous le souhaitez

Migration pour les applications C#

Étape 1 : Installer la bibliothèque NuGet

Pour une application WinUI 3, vous gérez l’activation pour les notifications à l’aide de la classe AppNotificationManager . Cette classe est fournie par le package Nuget Microsoft.WindowsAppSDK, qui est inclus par défaut dans les modèles de projet WinUI 3 Visual Studio.

Étape 2 : Mettre à jour votre manifeste

Dans votre package.appxmanifest, ajoutez :

  1. Déclaration pour xmlns:com
  2. Déclaration pour xmlns:desktop
  3. Dans l'attribut IgnorableNamespaces, com et desktop
  4. desktop :Extension pour windows.toastNotificationActivation pour déclarer votre CLSID d’activateur toast (à l’aide d’un nouveau GUID de votre choix).
  5. MSIX uniquement : com :Extension pour l’activateur COM à l’aide du GUID de l’étape 4. Veillez à inclure l’élément Arguments="----AppNotificationActivated:" afin que vous sachiez que votre lancement provient d’une notification
<!--Add these namespaces-->
<Package
  ...
  xmlns:com="http://schemas.microsoft.com/appx/manifest/com/windows10"
  xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"
  IgnorableNamespaces="... com desktop">
  ...
  <Applications>
    <Application>
      ...
      <Extensions>

        <!--Specify which CLSID to activate when app notification clicked-->
        <desktop:Extension Category="windows.toastNotificationActivation">
          <desktop:ToastNotificationActivation ToastActivatorCLSID="replaced-with-your-guid-C173E6ADF0C3" /> 
        </desktop:Extension>

        <!--Register COM CLSID LocalServer32 registry key-->
        <com:Extension Category="windows.comServer">
          <com:ComServer>
            <com:ExeServer Executable="YourProject.exe" Arguments="----AppNotificationActivated:" DisplayName="App notification activator">
              <com:Class Id="replaced-with-your-guid-C173E6ADF0C3" DisplayName="App notification activator"/>
            </com:ExeServer>
          </com:ComServer>
        </com:Extension>

      </Extensions>
    </Application>
  </Applications>
 </Package>

Étape 3 : Gérer l’activation

Dans le code de démarrage de votre application (généralement App.xaml.cs), mettez à jour votre code en procédant comme suit :

  1. Dans OnLaunched, obtenez l’instance par défaut de la classe AppNotificationManager .
  2. Inscrivez-vous à l’événement AppNotificationManager.NotificationInvoked .
  3. Appelez Microsoft.Windows.AppNotifications.AppNotificationManager.Register pour inscrire votre application pour recevoir des événements de notification. Il est important que votre appele cette méthode après l’inscription du gestionnaire NotificationInvoked .
  4. Refactorisez le code de lancement/d’activation de votre fenêtre dans une méthode d’assistance dédiée LaunchAndBringToForegroundIfNeeded , afin de pouvoir l’appeler à partir de plusieurs emplacements.
  5. Créez une HandleNotification méthode d’assistance afin qu’elle puisse être appelée à partir de plusieurs emplacements.
  6. Appelez AppInstance.GetActivatedEventArgs et vérifiez la propriété AppActivationArguments.Kind de l’objet retourné pour la valeur ExtendedActivationKind.AppNotification.
  7. Si le type d’activation n’est pas AppNotification, appelez la méthode d’assistance LaunchAndBringToForegroundIfNeededed.
  8. Si le type d’activation est AppNotification , castez la propriété AppActivationArguments.Data en un AppNotificationActivatedEventArgs et transmettez-la à la HandleNotification méthode d’assistance.
  9. Dans votre gestionnaire ApplicationManager.NotificationInvoked , appelez la méthode d’assistance HandleNotification .
  10. Dans votre HandleNotification méthode d’assistance, veillez à distribuer vers l’application ou le répartiteur de fenêtre avant d’exécuter un code lié à l’interface utilisateur, comme afficher une fenêtre ou mettre à jour l’interface utilisateur
  11. Migrez votre ancien code UWP OnActivated qui a géré l’activation des notifications d’application vers votre nouvelle HandleNotification méthode d’assistance.

App.xaml.cs migré


protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
    m_window = new MainWindow();

    // To ensure all Notification handling happens in this process instance, register for
    // NotificationInvoked before calling Register(). Without this a new process will
    // be launched to handle the notification.
    AppNotificationManager notificationManager = AppNotificationManager.Default;
    notificationManager.NotificationInvoked += NotificationManager_NotificationInvoked;
    notificationManager.Register();

    var activatedArgs = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs();
    var activationKind = activatedArgs.Kind;
    if (activationKind != ExtendedActivationKind.AppNotification)
    {
        LaunchAndBringToForegroundIfNeeded();
    } else
    {
        HandleNotification((AppNotificationActivatedEventArgs)activatedArgs.Data);
    }

}

private void LaunchAndBringToForegroundIfNeeded()
{
    if (m_window == null)
    {
        m_window = new MainWindow();
        m_window.Activate();

        // Additionally we show using our helper, since if activated via a app notification, it doesn't
        // activate the window correctly
        WindowHelper.ShowWindow(m_window);
    }
    else
    {
        WindowHelper.ShowWindow(m_window);
    }
}

private void NotificationManager_NotificationInvoked(AppNotificationManager sender, AppNotificationActivatedEventArgs args)
{
    HandleNotification(args);
}

private void HandleNotification(AppNotificationActivatedEventArgs args)
{
  // Use the dispatcher from the window if present, otherwise the app dispatcher
  var dispatcherQueue = m_window?.DispatcherQueue ?? DispatcherQueue.GetForCurrentThread();


  dispatcherQueue.TryEnqueue(async delegate
  {

      switch (args.Arguments["action"])
      {
          // Send a background message
          case "sendMessage":
              string message = args.UserInput["textBox"].ToString();
              // TODO: Send it

              // If the UI app isn't open
              if (m_window == null)
              {
                  // Close since we're done
                  Process.GetCurrentProcess().Kill();
              }

              break;

          // View a message
          case "viewMessage":

              // Launch/bring window to foreground
              LaunchAndBringToForegroundIfNeeded();

              // TODO: Open the message
              break;
      }
  });
}

private static class WindowHelper
{
    [DllImport("user32.dll")]
    private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    public static void ShowWindow(Window window)
    {
        // Bring the window to the foreground... first get the window handle...
        var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(window);

        // Restore window if minimized... requires DLL import above
        ShowWindow(hwnd, 0x00000009);

        // And call SetForegroundWindow... requires DLL import above
        SetForegroundWindow(hwnd);
    }
}

Création d’un contenu de notification d’application

Avec le Kit de développement logiciel (SDK) d’application Windows, vous pouvez toujours créer du contenu de notification d’application à l’aide de la nouvelle API AppNotificationsBuilder qui remplace la classe ToastContentBuilder fournie par windows Community Toolkit. Envoyez la notification d’application en appelant AppNotificationManager.Show. Il n’est pas recommandé de combiner windows Community Toolkit et les API du Kit de développement logiciel (SDK) d’application.

using Microsoft.Windows.AppNotifications;
using Microsoft.Windows.AppNotifications.Builder;

...

var builder = new AppNotificationBuilder()
    .AddText("Send a message.")
    .AddTextBox("textBox")
    .AddButton(new AppNotificationButton("Send")
        .AddArgument("action", "sendMessage"));

var notificationManager = AppNotificationManager.Default;
notificationManager.Show(builder.BuildNotification());