You can display a MessageBox in Rust by following these steps.
- Install Rust. See Getting Started with Rust.
- Run
cargo new --bin message_box in the command prompt. - Navigate to the
message_box directory. - Open
Cargo.toml and modify it as follows:
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"] }
|
This example targets Windows. Microsoft’s windows-sys provides raw FFI declarations for Windows APIs. MessageBoxW takes UTF-16 strings, and the FFI call must be inside unsafe.
- Open
src\main.rs and modify it as follows:
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,
);
}
}
|
Run cargo run in the command prompt.

If you want to build a release version, run cargo build --release.
References