8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

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

ウィンドウのタイトルを取得してみる

EnumWindowsを使ってみましょう。今回は Windows の世界の UTF-16 を Rust の世界の UTF-8 に変換するところが味噌です。

まずは Cargo.toml から。

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()&u16u16にしています。

main.rs
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編

8
2
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
8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?