without_library/
without_library.rs

1// How to create a toast without using this library
2
3extern crate xml;
4use std::path::Path;
5use xml::escape::escape_str_attribute;
6
7// You need to have the windows crate in your Cargo.toml
8// with the following features:
9//    "Data_Xml_Dom"
10//    "UI_Notifications"
11use windows::{
12    Data::Xml::Dom::XmlDocument,
13    UI::Notifications::ToastNotification,
14    UI::Notifications::ToastNotificationManager,
15};
16
17pub use windows::runtime::{
18    Error,
19    HSTRING,
20};
21
22fn main() {
23    do_toast().expect("not sure if this is actually failable");
24    // this is a hack to workaround toasts not showing up if the application closes too quickly
25    // you can put this in do_toast if you want.
26    std::thread::sleep(std::time::Duration::from_millis(10));
27}
28
29fn do_toast() -> windows::runtime::Result<()> {
30    let toast_xml = XmlDocument::new()?;
31
32    toast_xml.LoadXml(HSTRING::from(
33        format!(r#"<toast duration="long">
34                <visual>
35                    <binding template="ToastGeneric">
36                        <text id="1">title</text>
37                        <text id="2">first line</text>
38                        <text id="3">third line</text>
39                        <image placement="appLogoOverride" hint-crop="circle" src="file:///c:/path_to_image_above_toast.jpg" alt="alt text" />
40                        <image placement="Hero" src="file:///C:/path_to_image_in_toast.jpg" alt="alt text2" />
41                        <image id="1" src="file:///{}" alt="another_image" />
42                    </binding>
43                </visual>
44                <audio src="ms-winsoundevent:Notification.SMS" />
45                <!-- <audio silent="true" /> -->
46            </toast>"#,
47        escape_str_attribute(&Path::new("C:\\path_to_image_in_toast.jpg").display().to_string()),
48    ))).expect("the xml is malformed");
49
50    // Create the toast and attach event listeners
51    let toast_template = ToastNotification::CreateToastNotification(toast_xml)?;
52
53    // If you have a valid app id, (ie installed using wix) then use it here.
54    let toast_notifier = ToastNotificationManager::CreateToastNotifierWithId(HSTRING::from(
55        "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe",
56    ))?;
57
58    // Show the toast.
59    // Note this returns success in every case, including when the toast isn't shown.
60    toast_notifier.Show(&toast_template)
61}