AttachThreadInput in the callback of SetWindowsHookExA makes Microsoft Pinyin IME buggy when typing fast.

D T 25 Reputation points
2024-03-01T06:56:05.26+00:00

When I use AttachThreadInput in the callback of SetWindowsHookExA, and use Microsoft Pinyin IME in Chinese mode, and typing really fast, the IME turns buggy.

Minimal reproduction code (in rust, minified from rdev):

#[cfg(test)]
mod tests {
    use std::os::raw::c_int;
    use std::ptr::null_mut;
    use winapi::shared::minwindef::{LPARAM, LRESULT, WPARAM};
    use winapi::um::errhandlingapi::GetLastError;
    use winapi::um::processthreadsapi::GetCurrentThreadId;
    use winapi::um::winuser::{self, GetMessageA, SetWindowsHookExA, WH_KEYBOARD_LL};

    #[test]
    fn hook_and_block() {
        unsafe {
            if SetWindowsHookExA(WH_KEYBOARD_LL, Some(test_callback), null_mut(), 0).is_null() {
                let error = GetLastError();
                panic!("Error: {}", error);
            }
            GetMessageA(null_mut(), null_mut(), 0, 0);
        }
    }

    unsafe extern "system" fn test_callback(code: c_int, param: WPARAM, lpdata: LPARAM) -> LRESULT {
        unsafe {
            let current_window_thread_id = 14148;
            let thread_id = GetCurrentThreadId();
            if winuser::AttachThreadInput(thread_id, current_window_thread_id, 1) == 1 {
                println!("attached");

                winuser::AttachThreadInput(thread_id, current_window_thread_id, 0);
                println!("detached");
            }
            // CallNextHookEx(null_mut(), code, param, lpdata);
        }
        0
    }
}
Windows development Windows API - Win32
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.