How to keep focus on first thread when using AttachThreadInput?

Viewed 75

I found that by utilizing the APIs AttachThreadInput() and SetFocus(), I was able to click on a specific window when it's in the background, however it stole the focus from the first thread guiThreadID to the second target_window, and this happens only in case guiThreadID is currently focused.

If I have any other window focused while running the code, it doesn't get the focus stolen. The goal is to be able to click in the background window without activating it.

What can I try to avoid it stealing focus from the first thread?

HWND target_window = FindWindow(L"Test", NULL);

DWORD guiThreadID = GetCurrentThreadId();

bool threads_are_attached = false;
DWORD target_thread = GetWindowThreadProcessId(target_window, NULL);
if (target_thread && target_thread != guiThreadID && !IsWindowHung(target_window))
    threads_are_attached = AttachThreadInput(guiThreadID, target_thread, TRUE) != 0;

SetFocus(target_window);

auto lParam = MAKELPARAM(150, 700);
PostMessageW(target_window, WM_LBUTTONDOWN, 0x0001, lParam);
PostMessageW(target_window, WM_LBUTTONUP, 0, lParam);
0 Answers
Related