Holy cow, I wrote a book!
Some people didn't take to heart my cautions on the subject
of attached input queues, item number five on the list of
five things every Win32 programmer should know.
And then they find that their application stops responding.
// Code in italics is wrong
void TryToStealFocus(HWND hwnd)
// First try plain SetForegroundWindow
HWND hwndFG = GetForegroundWindow();
if (hwndFG == hwnd) return;
// That didn't work - if the foreground window belongs
// to another thread, attach to that thread and try again
DWORD dwCurrentThread = GetCurrentThreadId();
DWORD dwFGThread = GetWindowThreadProcessId(hwndFG, NULL);
if (dwFGThread == dwCurrentThread) return;
AttachThreadInput(dwCurrentThread, dwFGThread, TRUE);
SetForegroundWindow(hwnd); // hangs here
AttachThreadInput(dwCurrentThread, dwFGThread, FALSE);
Their customer feedback data shows that this function often
hangs at the second call to SetForegroundWindow.
My exercise for you is to explain why.
someone else with the same problem.)
(Note that both of these customers are trying to circumvent
the foreground lock timeout so that they can steal focus and shove
a dialog box in the user's face.)