Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Una notificación de aplicación es un elemento emergente de la interfaz de usuario que aparece fuera de la ventana de la aplicación, lo que proporciona información oportuna o acciones al usuario. Las notificaciones pueden ser puramente informativas, pueden iniciar la aplicación cuando se hace clic o pueden desencadenar una acción en segundo plano sin llevar la aplicación al primer plano.
Este artículo le guía por los pasos para crear y enviar una notificación de aplicación desde una aplicación de .NET y, a continuación, controlar la activación cuando el usuario interactúa con ella. En este artículo se usan las API de SDK de Aplicaciones para WindowsMicrosoft.Windows.AppNotifications.
Para obtener información general sobre las notificaciones de aplicaciones y las instrucciones de otros marcos, consulte Introducción a las notificaciones de aplicaciones.
En este artículo se tratan las notificaciones locales. Para obtener información sobre cómo entregar notificaciones desde un servicio en la nube, consulte Notificaciones push.
Importante
Actualmente no se admiten las notificaciones de aplicaciones con privilegios elevados (administradores).
Requisitos previos
- Un proyecto de aplicación de WPF o WinForms que tenga como destino .NET 6 o posterior.
- Debe configurar el proyecto para:
- Llamar a las APIs de tiempo de ejecución de Windows
- Usa el SDK de Aplicaciones para Windows
Registro para notificaciones de aplicaciones
En su App.xaml.cs, regístrese para recibir notificaciones en el controlador de eventos Startup. Debe registrar el controlador NotificationInvokedantes de llamar a Register.
En primer lugar, actualice App.xaml para usar un Startup controlador de eventos en lugar de 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>
A continuación, implemente la lógica de control de notificaciones y inicio:
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);
}
}
En Program.cs, regístrese para recibir notificaciones antes de llamar a Application.Run(). Debe registrar el controlador NotificationInvoked antes de llamar a Register.
Program.cs
using Microsoft.Windows.AppNotifications;
namespace WinFormsNotifications;
static class Program
{
[STAThread]
static void Main()
{
// Register the notification handler before calling Register
AppNotificationManager.Default.NotificationInvoked += OnNotificationInvoked;
AppNotificationManager.Default.Register();
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
// Unregister when the app exits
AppNotificationManager.Default.Unregister();
}
private static void OnNotificationInvoked(
AppNotificationManager sender,
AppNotificationActivatedEventArgs args)
{
// NotificationInvoked is raised on a background thread,
// so use Control.Invoke to marshal to the UI thread
var form = Application.OpenForms.Count > 0
? Application.OpenForms[0] as Form1
: null;
form?.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".
});
}
}
Importante
Debe llamar a Register antes de llamar a AppInstance.GetCurrent().GetActivatedEventArgs(). El NotificationInvoked controlador debe registrarse antes de que Register() sea llamado.
Nota
En el caso de las aplicaciones sin empaquetar, Register() configura automáticamente el registro del servidor COM que permite que Windows inicie la aplicación cuando se hace clic en una notificación. No es necesario configurar manualmente la activación COM ni un AUMID.
Envío de una notificación de aplicación
Use AppNotificationBuilder para construir contenido de notificación y AppNotificationManager.Show para enviar una notificación.
MainWindow.xaml.cs
Form1.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);
}
Para obtener información sobre cómo agregar botones, imágenes, entradas y otro contenido enriquecido a las notificaciones, consulte Contenido de notificación de la aplicación.
Configuración de la aplicación empaquetada
En el caso de las aplicaciones de .NET sin empaquetar, Register() controla automáticamente el registro COM. Para las aplicaciones empaquetadas (MSIX), debe agregar las siguientes extensiones 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
El Executable atributo debe contener solo el nombre de archivo ejecutable (por ejemplo, YourApp.exe), no una ruta de acceso de subdirectorio.