title: Win32 SetForegroundWindow unreliable
body: <p>I have a rather complex series of applications which depend on the ability to switch applications in the foreground.</p>
  
  <p>My problem is, every 5 or 6 times of switching the applications in the foreground, it simply fails to bring the application forward. GetLastError does not report any issues. Often times I see the correct application flash in the foreground for a moment then the previous application is visible.</p>
  
  <p>I have a Manager application which I have source for, it spawns and controls about 4 applications which I do not have source for. one of the applications it spawns/controls is also a manager which spawns/controls about 5 applications.</p>
  
  <p>This is a sort of kiosk design so the user wont even have a keyboard or mouse, just a touch screen.</p>
  
  <p>I have tried every combination of the Win32 calls to control them I am just out of ideas.</p>
  
  <p>My first attempt was:</p>
  
  <pre><code>SetWindowPos(hApp, HWND_TOPMOST, NULL, NULL, NULL, NULL, SWP_NOMOVE | SWP_NOSIZE);
  SetWindowPos(hApp, HWND_NOTOPMOST, NULL, NULL, NULL, NULL, SWP_NOMOVE | SWP_NOSIZE);
  </code></pre>
  
  <p>My second attempt was:</p>
  
  <pre><code>SetForegroundWindow(hApp);
  SetActiveWindow(hApp);
  SetFocus(hApp);
  </code></pre>
  
  <p>my third attempt:
      DWORD dwThreadID = GetWindowThreadProcessId(hApp, NULL);
      AttachThreadInput( dwThreadID, GetCurrentThreadId(), true);</p>
  
  <pre><code>SetForegroundWindow(hApp);
  SetActiveWindow(hApp);
  SetFocus(hApp);
  
  AttachThreadInput( dwThreadID, GetCurrentThreadId(), false);
  </code></pre>
  
  <p>my forth attempt:</p>
  
  <pre><code>DWORD dwThreadID = GetWindowThreadProcessId(hApp, NULL);
  AttachThreadInput( dwThreadID, GetCurrentThreadId(), true);
  
  SetWindowPos(hApp, HWND_TOPMOST, NULL, NULL, NULL, NULL, SWP_NOMOVE | SWP_NOSIZE);
  SetWindowPos(hApp, HWND_NOTOPMOST, NULL, NULL, NULL, NULL, SWP_NOMOVE | SWP_NOSIZE);
  
  SetForegroundWindow(hApp);
  SetActiveWindow(hApp);
  SetFocus(hApp);
  
  AttachThreadInput( dwThreadID, GetCurrentThreadId(), false);
  </code></pre>
  
  <p>I feel like I am missing an important gotcha when it comes to window switching. I know that only the foreground process can switch windows around but as my main Manager program is spawning and starting all the other processes which I need to control, I feel like it should be capable of moving these windows around. Any suggestions or advice is appreciated.</p>