如何将“宽”字符串读入缓冲区?

时间:2018-10-07 21:39:58

标签: winapi rust widestring

Windows API具有类似GetWindowTextW的功能,可将字符串读入您提供的缓冲区中。如何提供这样的缓冲区,然后在Rust中从中读取一个字符串?

P.S。 与该问题Calling the GetUserName WinAPI function with a mutable string doesn't populate the string相比,该问题通常侧重于Windows上的字符串读取,而不是特定的问题。另外,希望可以通过关键字轻松搜索该问题,回答要求的内容。

1 个答案:

答案 0 :(得分:0)

示例:

#[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()
}

溶液取自Calling the GetUserName WinAPI function with a mutable string doesn't populate the string

相关问题