devxlogo

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.

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.

See also  How Engineering Leaders Spot Weak Proposals

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.