環境
toolchain: stable-i686-pc-windows-msvc
rustc 1.32.0 (9fda7c223 2019-01-16)
winapi 0.3.6
ウィンドウのタイトルを取得してみる
EnumWindows
を使ってみましょう。今回は Windows の世界の UTF-16 を Rust の世界の UTF-8 に変換するところが味噌です。
まずは Cargo.toml から。
[dependencies.winapi]
version = "0.3"
features = ["winuser"]
main.rs をまとめてどうぞ。
UTF-16 を UTF-8 に変換しているのはdecode
関数です。std::char::decode_utf16()
は引数でIterator
受け取るのでスライスをsource.iter()
しています。そして.take_while(|&i| *i != 0)
でNULL終端文字までを抜き出しています。最後に.cloned()
で&u16
をu16
にしています。
use winapi::{
um::winuser::{EnumWindows, GetWindowTextW},
shared::{
windef::{HWND},
minwindef::{LPARAM, BOOL, TRUE}
},
};
use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
fn main() {
unsafe {
EnumWindows(Some(enum_proc), 0);
}
}
unsafe extern "system" fn enum_proc(hwnd: HWND, _l_param: LPARAM) -> BOOL {
let mut buf = [0u16; 1024];
if GetWindowTextW(hwnd, &mut buf[0], 1024) > 0 {
let win_text = decode(&buf);
println!("{}", win_text);
}
TRUE
}
fn decode(source: &[u16]) -> String {
decode_utf16(source.iter().take_while(|&i| *i != 0).cloned())
.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
.collect()
}
次回は EnumWindow で見つけた特定のウィンドウにキーボードイベントを送ってみたいと思います。
Rust で Windows プログラミング - SendInput編
今までのネタ
Rust で Windows プログラミング - MessageBox編
Rust で Windows プログラミング - CreateWindow編
Rust で Windows プログラミング - Shell_NotifyIcon編