首页 > 解决方案 > 我在 Rust/WinRT 中的 toast 通知程序需要 thread::sleep

问题描述

我是 WinRT 的新手。我写了一个 Rust/WinRT 代码来在 Win10 上推送一个 toast 通知。我的代码似乎工作正常,但我有 2 个关于 Rust/WinRT 的问题。

这是我的代码。

winrt::import!(
    dependencies
        os
    types
        windows::ui::notifications::*
);

use windows::ui::notifications::{
    ToastNotificationManager, ToastTemplateType, ToastNotification,
};

fn main() -> winrt::Result<()> {
    let notification = {
        let toast_xml = ToastNotificationManager::get_template_content(ToastTemplateType::ToastText01)?;

        let text_node = toast_xml.get_elements_by_tag_name("text")?.item(0)?;
        let text = toast_xml.create_text_node("Hello from Rust/WinRT!")?;
        text_node.append_child(text)?;

        ToastNotification::create_toast_notification(toast_xml)?
    };
    
    ToastNotificationManager::get_default()?
        .create_toast_notifier_with_id("{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe")?
        .show(notification)?;

    std::thread::sleep(std::time::Duration::from_millis(10));
    Ok(())
}

它按我的预期工作,但我有两个问题。

  1. text_node是不可变的。但是,我的代码似乎改变了它们。为什么不需要可变性?(也就是说,为什么windows::data::xml::dom::IXmlNode::append_child(&self, new_child: __0)不需要&mut self?)
  2. 如果我删除thread::sleep,则该程序结束而不推送 toast 通知。为什么?MS Docs中的JavaScript 示例不需要它。

请注意,我使用的是 Win10 Pro v1909 build 18363.778、Rust 1.44.0 stable-x86_64-pc-windows-msvc 和 winrt 0.7.0。

标签: windowsrustwindows-runtime

解决方案


推荐阅读