在 windows 上使用 rust 调用系统弹窗

文章目录

    想在 Windows 上执行一段 rust 的处理程序,处理完成后,能弹窗提醒任务完成。

    参考 Windows 官方的一个示例:

    https://learn.microsoft.com/en-us/windows/dev-environment/rust/rss-reader-rust-for-windows#showing-a-message-box

    创建项目

    cargo new rust_txt
    

    依赖

    Cargo.toml

    [package]
    name = "rust_txt"
    version = "0.1.0"
    edition = "2021"
    
    # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
    
    [dependencies]
    
    [dependencies.windows]
    version = "0.43.0"
    features = [
        "Win32_Foundation",
        "Win32_UI_WindowsAndMessaging",
    ]
    

    这是微软官方封装的一个库:

    https://github.com/microsoft/windows-rs

    里面功能十分强大,不但涵盖了 windows 系统接口,还包含了 http 请求,xml 文件解析等等各类功能。简直就是个全能工具箱。

    代码

    use windows::{
        core::*,    // Type support for the windows crate
        Win32::UI::WindowsAndMessaging::*
    };
    
    fn main() {
        println!("Hello, world!");
        unsafe {
            MessageBoxA(None, s!("Ansi"), s!("World"), MB_OK);
            MessageBoxW(None, w!("Wide"), w!("World"), MB_OK);
        }
    }
    

    执行效果

    $ cargo.exe run
    

    rust windows message box

    神奇的 exe 文件大小

    cargo.exe build --release
    

    编译之后生成的 release 版本的 exe 可执行文件大小只有 143K。。。

    而 cargo run 生成的 debug 版本大小,也只有 148K。。。

    震惊了。

    其他

    配合 VSCode 上的 rust-analyzer 插件,可以方便的查看相关 win32 函数的文档。

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式