Sometimes a function returns NULL because NULL really is the answer

Raymond Chen

Raymond

A customer reported that sometimes the Get­GUI­Thread­Info function returned a valid window handle, but sometimes it returned all NULLs.

  DWORD dwThreadId = GetWindowThreadProcessId(hwnd, NULL);
  GUITHREADINFO guiThreadInfo;
  guiThreadInfo.cbSize = sizeof(GUITHREADINFO);
  if (GetGUIThreadInfo(dwThreadId, &guiThreadInfo)) {
   HWND hwndActive = guiThreadInfo.hwndActive;
   ...
  }

Most of the time, the call to Get­GUI­Thread­Info succeeds and obtains hwndActive successfully. But sometimes, Get­GUI­Thread­Info succeeds, but guiThreadInfo.hwndActive is NULL. In fact, aside from the cbSize, all the members of the guiThreadInfo are NULL or zero. “Under what circumstances will Get­GUI­Thread­Info succeed but return no data?”

I suggested that they start with the obvious: Is it possible that the function is correct and the thread has no active window?

The customer confessed that they were too quick to assume that there was a problem with the Get­GUI­Thread­Info function just because it reported no data. It turns out that, in fact, there was no data to report.

The root cause was that another thread in their program called Set­Window­Pos and didn’t pass the SWP_NO­ACTIVATE flag. As a result, that thread stole activation from the first thread, so when they got around to asking the first thread, “Tell me about your active window, your focus window, your caret window, and your caret location,” it replied, “I don’t have any of those things!”

Raymond Chen
Raymond Chen

Follow Raymond