Using SetForegroundWindow on Windows Owned by Other Processes

Using SetForegroundWindow on Windows Owned by Other Processes

In modern versions of Windows (XP, Vista, and beyond), the API call SetForegroundWindow() will bring the specified window to the foreground only if it’s owned by the calling thread. The following code removes this limitation and provides a workaround:

void NewSetForegroundWindow(HWND hWnd){   if (GetForegroundWindow() != hWnd) {      DWORD dwMyThreadID = GetWindowThreadProcessId            (GetForegroundWindow(), NULL);      DWORD dwOtherThreadID = GetWindowThreadProcessId(hWnd, NULL);      if (dwMyThreadID != dwOtherThreadID) {         AttachThreadInput(dwMyThreadID, dwOtherThreadID, TRUE);         SetForegroundWindow(hWnd);         SetFocus(hWnd);         AttachThreadInput(dwMyThreadID, dwOtherThreadID, FALSE);      }      else         SetForegroundWindow(hWnd);      if (IsIconic(hWnd))         ShowWindow(hWnd, SW_RESTORE);      else         ShowWindow(hWnd, SW_SHOW);   }}

Another (but more intrusive and restrictive) way to make SetForegroundWindow() behave the same way as it did on Windows 95 and Microsoft Windows NT 4.0 is to change the foreground lock timeout value SPI_SETFOREGROUNDLOCKTIMEOUT, as described in this MSDN document.


Share the Post: