Windows.UI.Notifications is missing

You have to fight Visual Studio pretty hard to use these UWP contracts in a Winforms app. You got off on the wrong foot right away with the wrong TargetPlatformVersion, pretty hard to recover from that. Full steps to take:

Edit the .csproj file with a text editor, Notepad will do. Insert this:

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

Which assumes you have the 10586 SDK version installed on your machine. Current right now, these versions change quickly. Double-check by looking in the C:\Program Files (x86)\Windows Kits\10\Include with Explorer, you see the installed versions listed in that directory.

Open the Winforms project, use Project > Add Reference > Windows tab > tick the Windows.Data and the Windows.UI contract. Add Reference again and use the Browse tab to select System.Runtime. I picked the one in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\ .NETFramework\v4.6.1\Facades. This reference displays with a warning icon, not sure what it is trying to say but it doesn't appear to have any side-effects.

Test it by dropping a button on the form, double-click to add the Click event handler. The most basic code:

using Windows.UI.Notifications;
...

private void button1_Click(object sender, EventArgs e) {
    var xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
    var text = xml.GetElementsByTagName("text");
    text[0].AppendChild(xml.CreateTextNode("Hello world"));
    var toast = new ToastNotification(xml);
    ToastNotificationManager.CreateToastNotifier("anythinggoeshere").Show(toast);
}

Embellish by using a different ToastTemplateType to add an image or more lines of text. Do keep in mind that your program can only work on a Win10 machine.


If anyone should happen to stumble on this, see this similar but newer post -

Toast Notifications in Win Forms .NET 4.5

Read Stepan Hakobyan's comment at the bottom.

Essentially, I'm seeing the same thing. This code runs, I can step through it line by line with no exceptions but the toast notification is never shown within a Form app.

Tags:

C#

Winforms