下記の手順でRustでMessageBoxを表示することができます。
- Rustをインストールする。 Rustのはじめかた 参照
- コマンドプロンプトで
cargo new --bin message_boxを実行する。 MessageBoxディレクトリに移動する。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を実行する。
参考