Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Aug 25, 2009

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.

Alexander Ocher
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap