アプリ通知は、アプリのウィンドウの外側に表示される UI ポップアップで、タイムリーな情報やアクションをユーザーに提供します。 通知は、純粋に情報に関する情報である場合や、クリックされたときにアプリを起動したり、アプリをフォアグラウンドに移動せずにバックグラウンド アクションをトリガーしたりできます。
この記事では、WinForms アプリからアプリ通知を作成して送信し、ユーザーが操作するときにアクティブ化を処理する手順について説明します。 この記事では、Windows アプリ SDKMicrosoft.Windows.AppNotifications API を使用します。
アプリ通知の概要と他のフレームワークのガイダンスについては、「 アプリ通知の概要」を参照してください。
この記事では、ローカル通知について説明します。 クラウド サービスからの通知の配信については、「 プッシュ通知」を参照してください。
Important
管理者権限アプリの通知は現在サポートされていません。
前提条件
- .NET 6 以降を対象とする WinForms アプリ
-
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>
アプリ通知に登録する
Program.csで、を呼び出すApplication.Run()通知に登録します。 Register を呼び出す前 に、NotificationInvoked ハンドラーを 登録する必要があります。
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".
});
}
}
注
パッケージ化されていないアプリの場合、Register() は COM サーバーの登録を自動的に設定し、通知がクリックされたときにWindowsがアプリを起動できるようにします。 COM のアクティブ化または AUMID を手動で構成する必要はありません。
アプリ通知を送信する
AppNotificationBuilder を使用して通知コンテンツを作成し、AppNotificationManager.Show を使用してフォームから通知を送信します。
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);
}
ボタン、画像、入力、その他のリッチ コンテンツを通知に追加する方法については、「 アプリ通知コンテンツ」を参照してください。
パッケージ アプリのセットアップ
パッケージ化されていない WinForms アプリの場合、 Register() は COM 登録を自動的に処理します。 パッケージ アプリ (MSIX) の場合は、 Package.appxmanifestに拡張機能を追加する必要があります。 必要なマニフェスト エントリについては、WPF記事の「
関連するコンテンツ
Windows developer