啟動與結束時, 增加訊息通知到 Windows 訊息通知中.
以下是程式範例,使用 C# .NET 8.0 加上 **Windows Toast Notification** 功能,
在應用程式啟動和結束時,向 **Windows 訊息通知中心** 發送通知。
---
### **必要套件**
我們需要使用 **Windows.UI.Notifications** 命名空間來發送通知。請確保安裝以下 NuGet 套件:
```bash
dotnet add package Microsoft.Windows.SDK.Contracts
dotnet add package Microsoft.Windows.ImplementationLibrary
```
---
### **程式碼範例**
#### **1. 建立通知功能**
此類別用於創建並顯示 Windows 的通知訊息:
```csharp
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;
public static class NotificationHelper
{
// 發送通知
public static void ShowNotification(string title, string message)
{
// 創建通知的 XML 內容
string toastXmlString = $@"
{title}
{message}
";
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(toastXmlString);
// 創建 Toast 通知
var toastNotification = new ToastNotification(xmlDocument);
var notifier = ToastNotificationManager.CreateToastNotifier("YourAppId");
notifier.Show(toastNotification);
}
}
```
---
#### **2. 在應用程式啟動與結束時發送通知**
在主程式中,於啟動和結束時分別觸發通知。
```csharp
using System;
public class Program
{
public static void Main(string[] args)
{
// 啟動時通知
NotificationHelper.ShowNotification("應用程式啟動", "你的應用程式已成功啟動。");
Console.WriteLine("應用程式正在執行,按任意鍵結束...");
Console.ReadKey(); // 模擬程式執行中
// 結束時通知
NotificationHelper.ShowNotification("應用程式結束", "你的應用程式已結束執行。");
}
}
```
---
### **運作原理**
1. **啟動通知**:
- 在應用程式啟動時,呼叫 `NotificationHelper.ShowNotification()` 發送「應用程式啟動」通知。
2. **結束通知**:
- 在程式執行完畢(結束前),再次呼叫 `NotificationHelper.ShowNotification()` 發送「應用程式結束」通知。
---
### **通知效果**
在程式執行期間,使用者會在 Windows 通知中心看到如下通知:
- **啟動通知**:應用程式已成功啟動。
- **結束通知**:應用程式已結束執行。
---
### **注意事項**
1. **通知權限**:
- 確保使用者的 Windows 通知設定已啟用,否則通知可能不會顯示。
2. **自訂應用程式識別**:
- `CreateToastNotifier("YourAppId")` 中的 `"YourAppId"` 可自訂為你的應用程式名稱,用於辨識通知來源。
3. **通知格式**:
- 可以在 XML 的 `` 部分自訂通知的版面設計,包括圖片或多行文字顯示。
---
如果需要進一步擴展(例如加入圖像或按鈕互動),請告訴我,我可以幫助你實現! 😊