Featured image of post 使用Rust和windows-sys显示Windows消息框(MessageBox)的方法

使用Rust和windows-sys显示Windows消息框(MessageBox)的方法

详细讲解在Rust中使用`windows-sys`和`windows-sys`包,通过调用Windows API来显示简单的消息框(MessageBox)的方法,从项目创建到代码实现一步步带您操作。

可以通过以下步骤在Rust中显示MessageBox。

  1. 安装Rust。参考 Rust入门
  2. 在命令提示符中执行 cargo new --bin message_box。
  3. 移动到 message_box 目录。
  4. 打开 Cargo.toml 并修改如下。
1
2
3
4
5
6
7
[package]
name = "message_box"
version = "0.1.0"
edition = "2021"

[dependencies]
windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging"] }

此示例面向Windows。Microsoft的windows-sys提供Windows API的原始FFI声明。MessageBoxW接收UTF-16字符串,FFI调用必须放在unsafe代码块中。

  1. 打开 src\main.rs 并修改如下。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use windows_sys::Win32::UI::WindowsAndMessaging::{
    MessageBoxW, MB_ICONINFORMATION, MB_OK,
};

fn wide_null(value: &str) -> Vec<u16> {
    value.encode_utf16().chain(std::iter::once(0)).collect()
}

fn main() {
    let text = wide_null("Hello, world!");
    let caption = wide_null("MessageBox Example");

    unsafe {
        MessageBoxW(
            std::ptr::null_mut(),
            text.as_ptr(),
            caption.as_ptr(),
            MB_OK | MB_ICONINFORMATION,
        );
    }
}
  1. 在命令提示符中执行 cargo run。 img.png

  2. 如果要进行发布构建,请执行 cargo build --release。

参考资料

Licensed under CC BY-NC-SA 4.0
最后更新于 2026/11/24 00:00 +0900
comments powered by Disqus