這需求主要就是有遇到,所以就才研究一下,畢竟提這需求的人很少,主要是跑 console 但是需要一個 Windows Notification 來提醒有事件發生
當然,然後執行環境是 .net6 再 Windows 裡面,我就想說應該叫一下 API 就好了,結果也是花了一點時間..T.T.. 碰到了就記錄一下吧
1. 首先,你先引入 Microsoft.Toolkit.Uwp.Notifications ,
這時候你貼上範例程式,你會發現你沒有辦法呼叫 .Show
new Microsoft.Toolkit.Uwp.Notifications.ToastContentBuilder()
.AddArgument("action", "viewConversation")
.AddArgument("conversationId", new Random().Next(1, 1000))
.AddText("Andrew sent you a picture")
.AddText("Check this out, The Enchantments in Washington!")
.Show(); // Not seeing the Show() method? Make sure you have version 7.0, and if you're using .NET 6 (or later), then your TFM must be net6.0-windows10.0.17763.0 or greater
這時候你會看到,基本上在範例上看到有句話
// Not seeing the Show() method? Make sure you have version 7.0, and if you're using .NET 6 (or later), then your TFM
must be net6.0-windows10.0.17763.0 or greater
2. 修改專案檔,如果你對專案檔點選屬性 根本做作不了啥事情,我這邊是 windows 10 ,只能選擇 7.0 ,記得目標OS 要先選成 Windows
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
new Microsoft.Toolkit.Uwp.Notifications.ToastContentBuilder()
.AddArgument("action", "viewConversation")
.AddArgument("conversationId", new Random().Next(1, 1000))
.AddText("Andrew sent you a picture")
.AddText("Check this out, The Enchantments in Washington!")
.Show(); // Not seeing the Show() method? Make sure you have version 7.0, and if you're using .NET 6 (or later), then your TFM must be net6.0-windows10.0.17763.0 or greater
GenerateToast("Console呼叫呼叫", AppDomain.CurrentDomain.BaseDirectory + "thumb.jpg", "這是主標題", "副標題", "內文內文內文內文內文內文內文內文內文");
Console.ReadLine();
}
public static void GenerateToast(string appid, string imageFullPath, string h1, string h2, string p1)
{
var template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);
var textNodes = template.GetElementsByTagName("text");
textNodes[0].AppendChild(template.CreateTextNode(h1));
textNodes[1].AppendChild(template.CreateTextNode(h2));
textNodes[2].AppendChild(template.CreateTextNode(p1));
if (File.Exists(imageFullPath))
{
var toastImageElements = template.GetElementsByTagName("image");
((XmlElement)toastImageElements[0]).SetAttribute("src", imageFullPath);
}
IXmlNode toastNode = template.SelectSingleNode("/toast");
((XmlElement)toastNode).SetAttribute("duration", "long");
var notifier = ToastNotificationManager.CreateToastNotifier(appid);
var notification = new ToastNotification(template);
notifier.Show(notification);
}