Condividi tramite


Usare le notifiche delle app con un'app console

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 console .NET 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 console di .NET destinata a .NET 6 o una 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

Nel tuo Main metodo, registra il gestore NotificationInvokedprima di chiamare Register. L'app console deve rimanere in esecuzione per ricevere i callback di attivazione quando si fa clic sulle notifiche.

Program.cs

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

// Register the notification handler before calling Register
AppNotificationManager.Default.NotificationInvoked += (sender, args) =>
{
    // Handle notification activation.
    // args.Argument contains the arguments from the notification
    // or button that was clicked, as key=value pairs separated
    // by '&', for example "action=acknowledge".
    Console.WriteLine($"Notification activated! Arguments: {args.Argument}");
};

AppNotificationManager.Default.Register();

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.

var notification = new AppNotificationBuilder()
    .AddArgument("action", "viewItem")
    .AddText("Console Notification")
    .AddText("This was sent from a console app using Windows App SDK.")
    .AddButton(new AppNotificationButton("Acknowledge")
        .AddArgument("action", "acknowledge"))
    .BuildNotification();

AppNotificationManager.Default.Show(notification);

Mantenere l'app in esecuzione

Affinché il NotificationInvoked gestore venga chiamato, l'app console deve essere ancora in esecuzione quando l'utente fa clic sulla notifica. Se l'app viene chiusa prima che l'utente interagisca con la notifica, il clic successivo avvierà a freddo un nuovo processo.

Console.WriteLine("Notification sent! Waiting for activation...");
Console.WriteLine("Press Enter to exit.");
Console.ReadLine();

// Unregister when the app exits
AppNotificationManager.Default.Unregister();

Esempio completo

Di seguito è riportato un esempio di codice Program.cs che invia una notifica e gestisce l'attivazione:

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

Console.WriteLine("Console App Notification Test");

// Step 1: Register for notification activation
AppNotificationManager.Default.NotificationInvoked += (sender, args) =>
{
    Console.WriteLine($"Notification activated! Arguments: {args.Argument}");
};

AppNotificationManager.Default.Register();

// Step 2: Send a notification
var notification = new AppNotificationBuilder()
    .AddArgument("action", "viewItem")
    .AddText("Console Notification")
    .AddText("This was sent from a console app using Windows App SDK.")
    .AddButton(new AppNotificationButton("Acknowledge")
        .AddArgument("action", "acknowledge"))
    .BuildNotification();

AppNotificationManager.Default.Show(notification);

// Step 3: Wait for user interaction
Console.WriteLine("Notification sent! Click it to test activation.");
Console.WriteLine("Press Enter to exit.");
Console.ReadLine();

AppNotificationManager.Default.Unregister();