How to read a "wide" string into a buffer?

322 Views Asked by At

The Windows API has functions like GetWindowTextW that read a string into a buffer you provide. How do I provide such a buffer and then read a string from it in Rust?

P.S. In contrast to this question Calling the GetUserName WinAPI function with a mutable string doesn't populate the string this question focuses on string reading on Windows in general, and not a particular problem. Also, this question will hopefully be easily googled by keywords, answering what was asked for.

1

There are 1 best solutions below

0
On

Example:

#[cfg(target_os = "windows")]
fn get_window_name(max_size: i32) -> String {
    let mut vec = Vec::with_capacity(max_size as usize);
    unsafe {
        let hwnd = user32::GetForegroundWindow();
        let err_code = user32::GetWindowTextW(hwnd, vec.as_mut_ptr(), max_size);
        assert!(err_code != 0);
        assert!(vec.capacity() >= max_size as usize);
        vec.set_len(max_size as usize);
    };
    String::from_utf16(&vec).unwrap()
}

Solution taken from Calling the GetUserName WinAPI function with a mutable string doesn't populate the string