首页 > 解决方案 > Win Forms .NET 4.5 中的 Toast 通知

问题描述

我已经搜索了许多与从 Win Form 创建 toast 通知有关的不同帖子,但是当通过这些帖子生成 toast 通知时出现错误。

System.Exception:找不到元素。(HRESULT 例外:0x80070490)。

我已经编辑了 csproj 文件并添加了以下内容:

  <PropertyGroup>
       <TargetPlatformVersion>10.0.10586</TargetPlatformVersion>
  </PropertyGroup>

并根据Windows.UI.Notifications 中的建议添加了对的引用Windows.DataWindows.UI对的引用System.Runtime.dll

using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using System.Windows.Forms;
using System;

namespace ToastNotify
{
    class Notify
    {
        public void GenerateToast(string header, string content)
        {
            ToastTemplateType toastTemplate = ToastTemplateType.ToastImageAndText02;

            XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);

            XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
            toastTextElements[0].AppendChild(toastXml.CreateTextNode(header));
            toastTextElements[1].AppendChild(toastXml.CreateTextNode(content));

            XmlNodeList toastImageElements = toastXml.GetElementsByTagName("image");
            ((XmlElement)toastImageElements[0]).SetAttribute("src", "..\\..\\Resources\\icon.ico");

            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
            ((XmlElement)toastNode).SetAttribute("duration", "long");

            ToastNotification toast = new ToastNotification(toastXml);

            try
            {
                ToastNotificationManager.CreateToastNotifier().Show(toast);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());

            }
        }
    }
}

关于我哪里出错的任何建议?

标签: c#winformstoast

解决方案


您应该明确提供applicationIdCreateToastNotifier。

像这样:

private const String APP_ID = "Microsoft.Samples.DesktopToastsSample";
...
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast);

但我有个坏消息。从 Windows 10 1709 WinForms 应用程序开始不显示 toast 通知。在此之前 Show(toast) 工作,但现在它既不抛出异常,也不显示任何 toast 通知。

我还在想办法。

正如 Prateek Shrivastava 所指出的,有(新的)限制。

看看这里 https://docs.microsoft.com/en-us/uwp/api/windows.ui.notifications.toastnotificationmanager.createtoastnotifier

更新:
这是分步指南,使用 APP_ID 创建设置,以便通知适用于所有Windows 10 版本: 从桌面 C# 应用发送本地 toast 通知

更新:
无需设置即可在 Windows 10 1903 中再次运行。


推荐阅读