Adding Toast Messages to WPF Apps
As part of my job, I maintain a c# WPF app that we run on developers desktops. This app does things in the background for a while and if you have the app open then you get some feedback on where it is up to. But if you don’t have it open in front of you then you get nothing, so I went and added a toast notification and Taskbar Progress
Starting with the simple part, Taskbar Progress. When you download a file in Chrome or copy files from one folder to another, you see a little green progress bar on the icon.
For my app, when it is open in front of you, you can see the progress. It gives you a rough percentage of what is done. How can I show this on the toolbar? Well it turns out it’s rather simple.
In my model, I need 2 properties. The first is a percentage that says how much has been processed. I already had a property for this called StepsProcessed. The second property is the state that my app is in. This property needs to return System.Windows.Shell.TaskbarItemProgressState. Normally the Progress State is “None”.
When my app starts processing, I set ProgressState = Indeterminate. This causes the icon on the taskbar to pulse, showing that it is doing work but no indication of how much work is done.
Once I am able to calculate how much work needs doing, I set ProgressState = Normal. This causes it to set a progress bar based on my percentage of work done.
Finally, when the work is complete, I set the status back to None to remove the progress bar.
In the xaml of the window, I simply add:
<Window.TaskbarItemInfo> <TaskbarItemInfo ProgressValue="{Binding StepsProcessed}" ProgressState="{Binding ProgressState}" /> </Window.TaskbarItemInfo>
Done! Now when the application is running, a progress bar appears over the icon on the taskbar.
The second task was to add a little toast icon to the Windows Action Center – the little icon that appears near the clock. For example:
I wanted to add one of these when the process started and when the processed finished. Again, this turned out to be pretty simple, although it took a lot more work to actually get it to happen.
private void GenerateToast(string title, string message, string imagePath) { var template = ToastTemplateType.ToastImageAndText02; var toastXML = ToastNotificationManager.GetTemplateContent(template); var images = toastXML.GetElementsByTagName("image"); var imagePath = "file://" + imagePath; images[0].Attributes[1].NodeValue = imagePath; var textNodes = toastXML.GetElementsByTagName("text"); textNodes[0].AppendChild(toastXML.CreateTextNode(title)); textNodes[1].AppendChild(toastXML.CreateTextNode(message)); ToastNotificationManager.CreateToastNotifier("Application Name").Show(new Windows.UI.Notifications.ToastNotification(toastXML)); }
This method will accept the title, the message and a path to an image to use for the icon. Call the method, pass in all of the fields and a toast message pops up in the action center.