LoginSignup
9
5

More than 5 years have passed since last update.

Rust で Windows プログラミング - MessageBox編

Last updated at Posted at 2019-02-03

環境

toolchain: stable-i686-pc-windows-msvc
rustc 1.32.0 (9fda7c223 2019-01-16)
winapi 0.3.6

Hello, World!

MessageBox を呼び出すサンプルアプリを作ってみます。

Cargo.toml の編集から始めます。
必要に応じて features に使用する module を追加していきます。
version 0.3 から kernel-sys 等の -sys が付く crate は不要になっています。

Cargo.toml
[package]
name = "hellow_world"
version = "0.1.0"
authors = ["benki"]
edition = "2018"

[dependencies.winapi]
version = "0.3"
features = ["winuser"]

続いて main.rs。以前は一行目に extern crate winapi; を書いていましたが、edition = "2018" では不要になりました。

main.rs
use winapi::um::winuser::{MessageBoxW, MB_OK};
use std::ptr;

fn main() {
    unsafe {
        MessageBoxW(
            ptr::null_mut(), //hWnd: HWND
            encode("Hello, World!").as_ptr(), //lpText: LPCWSTR
            encode("こんにちわ、世界!").as_ptr(), //lpCaption: LPCWSTR
            MB_OK); //uType: UINT
    }
}

fn encode(source: &str) -> Vec<u16> {
    source.encode_utf16().chain(Some(0)).collect()
}

MessageBoxWの第一引数は親ウィンドウのHWNDですが、今回は使用しないので ptr::null_mut()を渡しています。
第二、第三引数はLPCWSTR型なので UTF-16 文字列へのポインタを渡せば良いのですが、Rust の文字コードは UTF-8 なので変換する必要があります。そこでencode関数で変換しています。std::str::encode_utf16()で UTF16 へ変換。.chain(Some(0))で NULL 終端文字を追加。.collect()Vec<u16>にまとめて戻り値としています。

次回はウィンドウを作ります。
Rust で Windows プログラミング - CreateWindow編

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5