S-JIS[2025-08-01] 変更履歴

Rust windows MessageBoxメモ

RustwindowsクレートのMessageBoxのメモ。


概要

Win32 APIのMessageBoxは、メッセージを表示するだけの単純なダイアログを表示する関数。
具体的にはMessageBoxAとMessageBoxW関数。


windowsクレートのMessageBoxを使うには、Win32_UI_WindowsAndMessagingフィーチャーを指定する。

Cargo.toml:

〜

[dependencies]
windows = { version = "0.61.3", features = ["Win32_UI_WindowsAndMessaging"] }

MessageBoxAの例

src/main.rs:

use windows::{
    core::PCSTR,
    Win32::UI::WindowsAndMessaging::{MessageBoxA, MB_OK},
};
fn main() {
    unsafe {
        MessageBoxA(
            None, // HWND
            PCSTR(b"message\0".as_ptr()),
            PCSTR(b"title\0".as_ptr()),
            MB_OK,
        );
    }
}

MessageBoxWの例

src/main.rs:

use windows::{
    core::PCWSTR,
    Win32::UI::WindowsAndMessaging::{MessageBoxW, MB_OK},
};
fn main() {
    let message = widestring("メッセージ");
    let title = widestring("タイトル");

    unsafe {
        MessageBoxW(
            None, // HWND
            PCWSTR(message.as_ptr()),
            PCWSTR(title.as_ptr()),
            MB_OK,
        );
    }
}
fn widestring(s: &str) -> Vec<u16> {
    use std::ffi::OsStr;
    use std::os::windows::ffi::OsStrExt;

    let mut v: Vec<u16> = OsStr::new(s).encode_wide().collect();
    v.push(0); // NUL終端
    v
}

windowsへ戻る / Rustへ戻る / 技術メモへ戻る
メールの送信先:ひしだま