Featured image of post How to Display a Windows Message Box (MessageBox) Using Rust and windows-sys

How to Display a Windows Message Box (MessageBox) Using Rust and windows-sys

Explains how to display a simple message box (MessageBox) by calling the Windows API using the `windows-sys` and `windows-sys` crates in Rust, following the steps from project creation to code implementation.

You can display a MessageBox in Rust by following these steps.

  1. Install Rust. See Getting Started with Rust.
  2. Run cargo new --bin message_box in the command prompt.
  3. Navigate to the message_box directory.
  4. 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.

  1. 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,
        );
    }
}
  1. Run cargo run in the command prompt. img.png

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

References

Licensed under CC BY-NC-SA 4.0
Last updated on 2026/11/24 00:00 +0900
comments powered by Disqus