I’m working on a program that uses low-level keyboard hooks (LowLevelKeyboardProc) to detect key combinations and switch focus between windows of specific processes. The goal is for the program to move focus to the next or previous window of a set of programs when detecting Shift + E or Shift + Q.
However, when the current window is not my own program’s window, the SetForegroundWindow function does not work, so I have to use AttachThreadInput to bring the window to the top. The problem is that the window does not receive focus, so when I send keyboard commands, they still go to the previous window.
How can I enable focus for the window that is on top?
Here is a snippet of the function I am using:
let target_window =
self.get_window_by_name(process_id, "Window Name".to_string());
if let Some(target_window) = target_window {
unsafe {
if current_process_id.is_none() {
ShowWindow(target_window.0, SW_NORMAL);
SetForegroundWindow(target_window.0);
SetActiveWindow(target_window.0);
} else {
let foreground_window = GetForegroundWindow();
let foreground_thread_id =
GetWindowThreadProcessId(foreground_window, std::ptr::null_mut());
let target_thread_id =
GetWindowThreadProcessId(target_window.0, std::ptr::null_mut());
AttachThreadInput(foreground_thread_id, target_thread_id, TRUE);
BringWindowToTop(target_window.0);
ShowWindow(target_window.0, SW_NORMAL);
// SetForegroundWindow(target_window.0);
// SetFocus(target_window.0);
SetActiveWindow(target_window.0);
AttachThreadInput(foreground_thread_id, target_thread_id, FALSE);
}
}
}