可以通过以下步骤在Rust中显示MessageBox。
- 安装Rust。参考 Rust入门
- 在命令提示符中执行
cargo new --bin message_box。 - 移动到
message_box 目录。 - 打开
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代码块中。
- 打开
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,
);
}
}
|
在命令提示符中执行 cargo run。

如果要进行发布构建,请执行 cargo build --release。
参考资料