WPF アプリでアプリ通知を使用する

アプリ通知は、アプリのウィンドウの外側に表示される UI ポップアップで、タイムリーな情報やアクションをユーザーに提供します。 通知は、純粋に情報に関する情報である場合や、クリックされたときにアプリを起動したり、アプリをフォアグラウンドに移動せずにバックグラウンド アクションをトリガーしたりできます。

アプリ通知のスクリーンショット

この記事では、WPF アプリからアプリ通知を作成して送信し、ユーザーが操作するときにアクティブ化を処理する手順について説明します。 この記事では、Windows アプリ SDKMicrosoft.Windows.AppNotifications API を使用します。

アプリ通知の概要と他のフレームワークのガイダンスについては、「 アプリ通知の概要」を参照してください。

この記事では、ローカル通知について説明します。 クラウド サービスからの通知の配信については、「 プッシュ通知」を参照してください。

Important

管理者権限アプリの通知は現在サポートされていません。

前提条件

  • .NET 6 以降を対象とするWPFアプリ
  • Windows アプリ SDK NuGet パッケージ (Microsoft.WindowsAppSDK)

プロジェクトを設定する

プロジェクト ファイル (.csproj) で、TargetFrameworkにWindowsターゲット フレームワークが含まれていることを確認します。

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

Windows アプリ SDK NuGet パッケージを追加します。

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

パッケージ化されていないアプリの場合は、次を追加します。

<WindowsPackageType>None</WindowsPackageType>

アプリ通知に登録する

App.xaml.csで、Startup イベント ハンドラーで通知に登録します。 Register を呼び出す前に、NotificationInvoked ハンドラーを登録する必要があります。

まず、App.xamlではなくStartupイベント ハンドラーを使用するように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>

次に、スタートアップおよび通知処理ロジックを実装します。

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);
    }
}

Important

Registerを呼び出す前に、AppInstance.GetCurrent().GetActivatedEventArgs()を呼び出す必要があります。 NotificationInvokedが呼び出される前に、Register() ハンドラーを登録する必要があります。

パッケージ化されていないアプリの場合、Register() は COM サーバーの登録を自動的に設定し、通知がクリックされたときにWindowsがアプリを起動できるようにします。 COM のアクティブ化または AUMID を手動で構成する必要はありません。

アプリ通知を送信する

AppNotificationBuilder を使用して通知コンテンツを作成し、AppNotificationManager.Show を使用して通知を送信します。

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);
}

ボタン、画像、入力、その他のリッチ コンテンツを通知に追加する方法については、「 アプリ通知コンテンツ」を参照してください。

パッケージ アプリのセットアップ

パッケージ化されていないWPF アプリの場合、Register() は COM 登録を自動的に処理します。 パッケージ アプリ (MSIX) の場合は、 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>

Important

Executable属性には、サブディレクトリ パスではなく、実行可能ファイル名 (YourApp.exe など) のみを含める必要があります。