Condividi tramite


Usare le notifiche delle app con un'app macchine virtuali Windows

Una notifica dell'app è un popup dell'interfaccia utente visualizzato all'esterno della finestra dell'app, fornendo informazioni o azioni tempestive all'utente. Le notifiche possono essere puramente informative, possono avviare l'app quando si fa clic o attivare un'azione in background senza portare l'app in primo piano.

Screenshot di una notifica dell'app

Questo articolo illustra i passaggi per creare e inviare una notifica dell'app da un'app macchine virtuali Windows e quindi gestire l'attivazione quando l'utente interagisce con esso. Questo articolo usa le API SDK per app di WindowsMicrosoft.Windows.AppNotifications.

Per una panoramica delle notifiche delle app e indicazioni per altri framework, vedere Panoramica delle notifiche delle app.

Questo articolo illustra le notifiche locali. Per informazioni sulla distribuzione di notifiche da un servizio cloud, vedere Notifiche push.

Importante

Le notifiche per le app con privilegi elevati (amministratore) non sono attualmente supportate.

Prerequisiti

  • Un'app macchine virtuali Windows destinata a .NET 6 o versione successiva
  • Il pacchetto NuGet SDK per app di Windows (Microsoft.WindowsAppSDK)

Configurare il progetto

Nel file di progetto (.csproj), assicurarsi che il TargetFramework includa un framework di destinazione Windows:

<TargetFramework>net9.0-windows10.0.19041.0</TargetFramework>

Aggiungere il pacchetto NuGet SDK per app di Windows:

<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.7.250310001" />

Per le app non in pacchetto, aggiungere:

<WindowsPackageType>None</WindowsPackageType>

Registrarsi per le notifiche dell'app

Per registrarsi alle notifiche nel Startup gestore eventi. È necessario registrare il gestore NotificationInvokedprima di chiamare Register.

Prima di tutto, aggiornare App.xaml per usare un Startup gestore eventi anziché StartupUri:

App.xaml

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

Implementare quindi la logica di gestione di avvio e notifica:

App.xaml.cs

using System.Windows;
using Microsoft.Windows.AppNotifications;

namespace WpfNotifications;

public partial class App : Application
{
    private void OnStartup(object sender, StartupEventArgs e)
    {
        // Register the notification handler before calling Register
        AppNotificationManager.Default.NotificationInvoked += OnNotificationInvoked;
        AppNotificationManager.Default.Register();

        // Show the main window
        var mainWindow = new MainWindow();
        mainWindow.Show();
    }

    private void OnNotificationInvoked(
        AppNotificationManager sender, 
        AppNotificationActivatedEventArgs args)
    {
        // NotificationInvoked is raised on a background thread,
        // so dispatch to the UI thread for any UI updates
        Current.Dispatcher.Invoke(() =>
        {
            // Parse args.Argument to determine what action to take.
            // args.Argument contains the arguments from the notification
            // or button that was clicked, as key=value pairs separated
            // by '&', for example "action=reply&conversationId=9813".
        });
    }

    protected override void OnExit(ExitEventArgs e)
    {
        AppNotificationManager.Default.Unregister();
        base.OnExit(e);
    }
}

Importante

È necessario chiamare Register prima di chiamare AppInstance.GetCurrent().GetActivatedEventArgs(). Il gestore deve essere registrato NotificationInvoked prima che Register() venga chiamato.

Annotazioni

Per le app non in pacchetto, Register() configura automaticamente la registrazione del server COM che consente Windows di avviare l'app quando si fa clic su una notifica. Non è necessario configurare manualmente l'attivazione COM o un AUMID.

Inviare una notifica dell'app

Usare AppNotificationBuilder per costruire il contenuto di notifica e AppNotificationManager.Show per inviare una notifica.

Mainwindow.xaml.cs

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

private void SendNotification()
{
    var notification = new AppNotificationBuilder()
        .AddArgument("action", "viewConversation")
        .AddArgument("conversationId", "9813")
        .AddText("Andrew sent you a picture")
        .AddText("Check this out, The Enchantments in Washington!")
        .BuildNotification();

    AppNotificationManager.Default.Show(notification);
}

Per informazioni sull'aggiunta di pulsanti, immagini, input e altro contenuto avanzato alle notifiche, vedi Contenuto delle notifiche dell'app.

Configurazione dell'app in pacchetto

Per le app di macchine virtuali Windows non in pacchetto, Register() gestisce automaticamente la registrazione COM. Per le app in pacchetto (MSIX), è necessario aggiungere le estensioni seguenti a Package.appxmanifest:

<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 notification is clicked-->
        <desktop:Extension Category="windows.toastNotificationActivation">
          <desktop:ToastNotificationActivation 
            ToastActivatorCLSID="YOUR-GUID-HERE" />
        </desktop:Extension>

        <!--Register COM CLSID-->
        <com:Extension Category="windows.comServer">
          <com:ComServer>
            <com:ExeServer 
              Executable="YourApp.exe" 
              Arguments="----AppNotificationActivated:" 
              DisplayName="YourApp">
              <com:Class Id="YOUR-GUID-HERE" />
            </com:ExeServer>
          </com:ComServer>
        </com:Extension>

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

Importante

L'attributo Executable deve contenere solo il nome del file eseguibile (ad esempio, YourApp.exe), non un percorso di sottodirectory.