Toast Notifications in Win Forms .NET 4.5

Ett*_*erz 3 c# toast

I've searched through a number of different posts to do with creating toast notifications from a Win Form however when these through I get an error when generating the toast notification.

System.Exception: Element not found. (Exception from HRESULT:0x80070490).

I have edited the csproj file and added the following:

  <PropertyGroup>
       <TargetPlatformVersion>10.0.10586</TargetPlatformVersion>
  </PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

and added the references to Windows.Data and Windows.UI and also a reference to System.Runtime.dll as per the suggestions in Windows.UI.Notifications is missing

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());

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Any suggestions as to where I am going wrong?

Ste*_*yan 5

您应该明确提供applicationIdCreateToastNotifier。

像这样:

private const String APP_ID = "Microsoft.Samples.DesktopToastsSample";
...
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast);
Run Code Online (Sandbox Code Playgroud)

但是我有个坏消息。从Windows 10 1709开始,WinForms应用程序仅不显示吐司通知。在该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中再次运行。

  • @Ali123 应用程序 ID 是自定义的。你弥补吧。这是您用来注册应用程序的字符串,这就是为什么他们建议使用“公司名称/产品名称”,这样就不会发生冲突。最终,虽然上面的 MS 示例链接看起来相当完整,但它是垃圾。不起作用。 (2认同)