Introduction
This is my first tip on adding a toast notification to a uwp app.
I'm not a professional programmer and don't intend to be one. Just as a hobby, I program small applications.
I have also created a very simple and very basic demonstration application. You can download the sourcecode.
Background
For work and hobby, I change USB Comm ports a lot. You always hear a sound but never see a message like 'Serial USB device COM5 inserted'. I have created only for my personal use a simple and basic program in C# for UWP. This program listens for USB insertions en checks if it is a serial port. Then when I insert a USB Comm port device I see a toast message with the text "device COM5 inserted". For my very handy.
Using the Code
To display a toast, you need to set up a simple template.
private void displayToastNotification(String caption, String message)
{
var toastTemplate = "<toast launch=\"app-defined-string\">" +
"<visual>" +
"<binding template =\"ToastGeneric\">" +
"<text>" + caption + "</text>" +
"<text>" + message + "</text>" +
"</binding>" +
"</visual>" +
"</toast>";
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(toastTemplate);
var toastNotification = new ToastNotification(xmlDocument);
var notification = ToastNotificationManager.CreateToastNotifier();
notification.Show(toastNotification);
}
When the user clicks the button 'Toast' a toast message appears.
private void btnToasTest_Click(object sender, RoutedEventArgs e)
{
displayToastNotification("Hello world!", "This is my message!");
}
When the user clicks the button 'Close' all toast messages are remove from notification center
private void btnCloseApp_Click(object sender, RoutedEventArgs e)
{
removeToastHistory();
Application.Current.Exit();
}
When the user closes the application, I want to clear the notifications too. I accomplished this with this simple function.
private void removeToastHistory()
{
var toastHistory = ToastNotificationManager.History;
toastHistory.Clear();
}
That's all....
Points of Interest
On the internet, I found a lot of examples how to create a toast notification but not how to neatly remove it when the application closes. I solved it like this.
History
- No history yet..... I might post my simple USB COMM port watcher application in the future. For now only the very simple and very basic application for the toast only.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.