首页 > 技术文章 > .net core 5 发送windows10桌面通知

axel10 2021-11-30 14:26 原文

先在csproj文件中添加或改变以下属性:

    <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net5.0-windows10.0.19041.0</TargetFramework>
    </PropertyGroup>

其中TargetFramework里面的windows版本号如果高于运行的系统将会报错。

  • net5.0-windows10.0.17763.0:如果应用面向 Windows 10 版本 1809。
  • net5.0-windows10.0.18362.0:如果应用面向 Windows 10 版本 1903。
  • net5.0-windows10.0.19041.0:如果应用面向 Windows 10 版本 2004。
  • net5.0-windows10.0.22000.0:如果应用面向 Windows 11。

具体查看官方文档:https://docs.microsoft.com/zh-cn/windows/apps/desktop/modernize/desktop-to-uwp-enhance

创建提醒方法:

        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))
            {
                XmlNodeList 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);
        }

调用:

            GenerateToast("12311","","123","456","aaa");

参考自https://stackoverflow.com/questions/65054564/netcore-show-windows-10-notification-toast

推荐阅读