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.
Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.























