August 1st, 2008

I warned you: The dangers of attaching input queues

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
  SetForegroundWindow(hwnd);
  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. (Here’s 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.)

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.

Feedback