このクイック スタートでは、Windows アプリ SDK を使用してローカル アプリ通知を送信して応答する WinUI アプリを作成します。
アプリ通知を実装する完全なサンプル アプリについては、GitHub の
Important
アプリ通知は、管理者特権 (管理者) アプリではサポートされていません。
Prerequisites
- Visual Studio 2022 (v17.6 以降) をインストールする
- C++ 開発用の C++ ワークロード、および C# 開発用の .NET ワークロードを含めます。
- .NETデスクトップ開発の MSIX パッケージ ツールが選択されていることを確認します。
- [アプリケーション開発Windows選択されていることを確認します。
- Windows UI アプリケーション開発を選択されていることを確認してください。
Visual Studioでのワークロードの管理の詳細については、「Modify Visual Studio ワークロード、コンポーネント、言語パックを参照してください。 WinUI の概要の詳細については、「 WinUI の概要」を参照してください。 既存のプロジェクトにWindows アプリ SDKを追加するには、「既存のプロジェクトでWindows アプリ SDKを使用するを参照してください。
Visual Studioで新しい WinUI アプリ プロジェクトを作成する
- Visual Studioで、新しいプロジェクトを作成します。
- [ 新しいプロジェクトの作成 ] ダイアログで、言語フィルターを "C#" または "C++" に設定し、プラットフォーム フィルターを "WinUI" に設定し、"Blank App, Packaged (WinUI 3 in Desktop)" プロジェクト テンプレートを選択します。
- 新しいプロジェクトに "AppNotificationsExample" という名前を付けます。
ローカル アプリ通知を送信する
このセクションでは、クリックされたときにローカル アプリ通知を送信するボタンをアプリに追加します。 通知には、テキスト コンテンツとアプリロゴイメージが含まれます。 また、ユーザーが通知をクリックしたときにアクティブ化引数を表示する 2 つの読み取り専用テキスト ボックスも追加します。
まず、 Button コントロールと 2 つの TextBox コントロールを MainWindow.xamlに追加します。
<!-- MainWindow.xaml -->
<Button x:Name="SendNotificationButton" Content="Send App Notification" Click="SendNotificationButton_Click"/>
<TextBlock Text="Activation arguments:" FontWeight="SemiBold" Margin="0,12,0,0"/>
<TextBox x:Name="ActionTextBox" Header="action" IsReadOnly="True" PlaceholderText="(none)"/>
<TextBox x:Name="ExampleEventIdTextBox" Header="exampleEventId" IsReadOnly="True" PlaceholderText="(none)"/>
アプリ通知 API は、Microsoft.Windows.AppNotifications および Microsoft.Windows.AppNotifications.Builder 名前空間にあります。 プロジェクトに次の参照を追加します。
// MainWindow.xaml.cs
using Microsoft.Windows.AppNotifications;
using Microsoft.Windows.AppNotifications.Builder;
次に、ボタン クリック ハンドラーに次のコードを追加します。 この例では 、AppNotificationBuilder を使用して通知コンテンツを作成します。これには、ユーザーが通知をクリックしたときにアプリに返される引数、アプリのロゴ イメージ、テキストが含まれます。 通知には、アプリの UI を起動せずにアクションを実行する方法を示すボタンも含まれています。 BuildNotification メソッドは AppNotification オブジェクトを作成し、AppNotificationManager.Show はそれをユーザーに表示します。
// MainWindow.xaml.cs
private void SendNotificationButton_Click(object sender, RoutedEventArgs e)
{
var appNotification = new AppNotificationBuilder()
.AddArgument("action", "NotificationClick")
.AddArgument("exampleEventId", "1234")
.SetAppLogoOverride(new System.Uri("ms-appx:///Assets/Square150x150Logo.png"), AppNotificationImageCrop.Circle)
.AddText("This is text content for an app notification.")
.AddButton(new AppNotificationButton("Perform action without launching app")
.AddArgument("action", "BackgroundAction"))
.BuildNotification();
AppNotificationManager.Default.Show(appNotification);
}
この時点で、アプリをビルドして実行できます。 [ アプリ通知の送信 ] ボタンをクリックして通知を表示します。 通知をクリックしてもアクションはまだ実行されません。次のセクションでは、ユーザーが通知をクリックしたときにアプリが応答できるように、アプリのアクティブ化を処理する方法について説明します。
Note
アプリが管理者特権 (昇格) で実行されている場合、アプリ通知はサポートされません。 表示 は自動的に失敗し、通知は表示されません。 通知をテストするときは、昇格せずにアプリを実行してください。
アプリ パッケージ マニフェスト ファイルを更新する
Package.appmanifest ファイルには、アプリの MSIX パッケージの詳細が表示されます。 ユーザーがアプリ通知を操作したときにアプリを起動できるようにするには、アプリパッケージマニフェストファイルを更新して、アプリがアプリ通知のアクティブ化のターゲットとしてシステムに登録されるようにする必要があります。 アプリ パッケージ マニフェストの詳細については、「アプリ パッケージ マニフェスト」を参照してください。
- Package.appxmanifest ファイルを編集するには、ソリューション エクスプローラーでファイルを右クリックし、 View Codeを選択します。
-
xmlns:com="http://schemas.microsoft.com/appx/manifest/com/windows10"名前空間とxmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"名前空間を<Package>に追加します。 -
<desktop:Extension>の下に<Extensions>要素を追加します。Category属性を"windows.toastNotificationActivation"に設定して、アプリ通知によってアプリをアクティブ化できることを宣言します。-
<desktop:ToastNotificationActivation>子要素を追加し、アプリを一意に識別する GUID にToastActivatorCLSIDを設定します。 - Visual Studioで GUID を生成するには、Tools > GUID の作成に移動します。
-
-
<com:Extension>の下に<Extensions>要素を追加し、Category属性を"windows.comServer"に設定します。 次に示すマニフェスト ファイルの例は、この要素の構文を示しています。-
Executable要素の<com:ExeServer>属性を実行可能ファイル名で更新します。 この例では、名前が"AppNotificationsExample.exe"されます。 -
Arguments="----AppNotificationActivated:"を指定して、Windows アプリ SDKが通知のペイロードを AppNotification の種類として処理できるようにします。 -
Id要素の<com:Class>属性を、ToastActivatorCLSID属性に使用したのと同じ GUID に設定します。
-
<!--package.appxmanifest-->
<Package
xmlns:com="http://schemas.microsoft.com/appx/manifest/com/windows10"
xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"
...
<Applications>
<Application>
...
<Extensions>
<!--Specify which CLSID to activate when notification is clicked-->
<desktop:Extension Category="windows.toastNotificationActivation">
<desktop:ToastNotificationActivation ToastActivatorCLSID="replaced-with-your-guid-C173E6ADF0C3" />
</desktop:Extension>
<!--Register COM CLSID-->
<com:Extension Category="windows.comServer">
<com:ComServer>
<com:ExeServer Executable="SampleApp.exe" DisplayName="SampleApp" Arguments="----AppNotificationActivated:">
<com:Class Id="replaced-with-your-guid-C173E6ADF0C3" />
</com:ExeServer>
</com:ComServer>
</com:Extension>
</Extensions>
</Application>
</Applications>
</Package>
アプリ通知からのアクティブ化を処理する
ユーザーがアプリ通知または通知内のボタンをクリックすると、アプリは適切に応答する必要があります。 次の 2 つの一般的なアクティブ化シナリオがあります。
- UI を使用して起動 する - ユーザーが通知本文をクリックすると、アプリが起動するかフォアグラウンドに移動し、関連するコンテンツが表示されます。
- バックグラウンド アクション - ユーザーは通知内のボタンをクリックし、アプリの UI を表示せずにアクション (返信の送信など) をトリガーします。
両方のシナリオをサポートするには、アプリのアクティブ化フローでメイン ウィンドウを OnLaunched に作成する必要がありますが、すぐにはアクティブ化 しないでください 。 代わりに、 AppNotificationManager.NotificationInvoked イベントを登録し、 AppNotificationManager.Register を呼び出し、 AppInstance.GetActivatedEventArgs を調べて、これが通常の起動であるか、 NotificationInvokedを待機する必要がある COM アクティブ化パスであるかを判断します。 その後、コードは、ウィンドウを表示するか、アクションをサイレント処理して終了するかを決定できます。
NotificationInvoked イベントは、アプリの実行中に発生するクリックを処理します。 アプリが実行されていない場合、Windowsは COM のアクティブ化によってアプリを起動し、アクティブ化の種類は Launch ではなく、AppNotification として報告されます。 通知引数は、 NotificationInvoked イベントを通じて配信されます。
Important
AppInstance.GetActivatedEventArgs を呼び出す前に、AppNotificationManager.Register を呼び出す必要があります。
Important
デスクトップ アプリの場合、通知 XML ペイロード内の activationType="background" の設定は無視されます。 コードでアクティブ化引数を処理し、ウィンドウを表示するかどうかを決定する必要があります。
// App.xaml.cs
using Microsoft.UI.Xaml;
using Microsoft.Windows.AppLifecycle;
using Microsoft.Windows.AppNotifications;
namespace AppNotificationsExample;
public partial class App : Application
{
private Window? _window;
public App()
{
InitializeComponent();
}
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
_window = new MainWindow();
AppNotificationManager.Default.NotificationInvoked += OnNotificationInvoked;
AppNotificationManager.Default.Register();
var activatedArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
if (activatedArgs.Kind == ExtendedActivationKind.AppNotification)
{
// App was launched by clicking a notification
var notificationArgs = (AppNotificationActivatedEventArgs)activatedArgs.Data;
HandleNotification(notificationArgs);
}
else
{
// Normal launch
_window.Activate();
}
}
private void OnNotificationInvoked(AppNotificationManager sender, AppNotificationActivatedEventArgs args)
{
// Notification clicked while app is already running
HandleNotification(args);
}
private void HandleNotification(AppNotificationActivatedEventArgs args)
{
var action = args.Arguments.ContainsKey("action") ? args.Arguments["action"] : "(none)";
var exampleEventId = args.Arguments.ContainsKey("exampleEventId") ? args.Arguments["exampleEventId"] : "(none)";
_window!.DispatcherQueue.TryEnqueue(() =>
{
switch (action)
{
case "BackgroundAction":
// Handle the action without showing the app window.
// If the window was never shown, exit the app.
if (!_window.Visible)
{
Application.Current.Exit();
}
break;
default:
// Bring the app to the foreground and display the notification arguments.
_window.Activate();
((MainWindow)_window).UpdateNotificationUI(action, exampleEventId);
break;
}
});
}
}
UpdateNotificationUI に MainWindow メソッドを追加して、前に追加したテキストボックスに通知引数を表示します。
// MainWindow.xaml.cs
public void UpdateNotificationUI(string action, string exampleEventId)
{
DispatcherQueue.TryEnqueue(() =>
{
ActionTextBox.Text = action;
ExampleEventIdTextBox.Text = exampleEventId;
});
}
次のステップ
- アプリ通知コンテンツ - 画像、ボタン、入力、その他の UI 要素を通知に追加する方法について説明します。
- アプリの通知を削除する - 通知 のタグ付け、削除、有効期限の設定を行う方法について説明します。
こちらも参照ください
Windows developer