1 using System;2 using System.Windows.Forms;3 using Windows.Data.Xml.Dom;4 using Windows.UI.Notifications;5 6 using System.Collections.Generic;7 using System.Linq;8 using System.Text;9 using System.Ru...

1 using System; 2 using System.Windows.Forms; 3 using Windows.Data.Xml.Dom; 4 using Windows.UI.Notifications; 5 6 using System.Collections.Generic; 7 using System.Linq; 8 using System.Text; 9 using System.Runtime.InteropServices; 10 11 namespace ST 12 { 13 public class Toast 14 { 15 public void showTheToast() 16 { 17 string xml = "<toast>" + 18 "<visual>" + 19 "<binding template=\"ToastGeneric\">" + 20 "<text>电池电量不足 " + 21 "</text>" + 22 "<text>请尽快接通电脑电源。</text>" + 23 "</binding>" + 24 "</visual>" + 25 "</toast>"; 26 XmlDocument doc = new XmlDocument(); 27 doc.LoadXml(xml); 28 ToastNotification notification = new ToastNotification(doc); 29 ToastNotifier nt = ToastNotificationManager.CreateToastNotifier(); 30 nt.Show(notification); 31 } 32 33 34 static void Main(string[] args) 35 { 36 Toast toast = new Toast(); 37 toast.showTheToast(); 38 } 39 } 40 }
此代码的作用是产生一个toast,但是生成exe的时候会出错。
System.Exception:“找不到元素。 (异常来自 HRESULT:0x80070490)”
原因在于没有给CreateToastNotifier()传入参数。根据一篇文章的说法,在Windows8之后,程序想要显示toast,必须指定一个appID,这个ID用来指明是什么程序产生的toast。查找这个ID的方法是打开powershell,输入get-StartApps,得到本地的appID列表。选择其中一个,比如说Chrome,代表谷歌浏览器,然后给CreateToastNotifier()传入参数,
ToastNotifier nt = ToastNotificationManager.CreateToastNotifier("Chrome");
就可以生成了,并且产生的toast还会指明是Chrome发出了这个toast。
当你“安装”了一个程序之后,也可以产生一个appID,所以如果你想要用自己的appID,就可以将自己的程序打包成安装程序,安装,将安装后的appID传入CreateToastNotifier()中。
本文标题为:用C#编写Windows10的toast的注意事项。


基础教程推荐
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- Unity shader实现高斯模糊效果 2023-01-16
- 实例详解C#实现http不同方法的请求 2022-12-26
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C# 解析XML和反序列化的示例 2023-04-14
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#中的Linq to JSON操作详解 2023-06-08