title: Understanding AttachThreadInput - detaching lose focus
body: <p>i got a little problem fully understanding AttachThreadInput.</p>
  
  <p>I know it's "connecting" the message queue of 2 threads, which (what i want to do) allows me for example to force my window (winforms) in foreground.</p>
  
  <p>Which I can do with this method:</p>
  
  <pre><code>private void SetForegroundWindowEx(IntPtr hWnd)
  {
      uint SW_SHOW = 5;
      uint appThread = GetCurrentThreadId();     
      uint foregroundThread = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);         
  
      if (foregroundThread != appThread)
      {
          AttachThreadInput(foregroundThread, appThread, true);
  
          BringWindowToTop(hWnd);
          ShowWindow(hWnd, SW_SHOW);       
          AttachThreadInput(foregroundThread, appThread, false);
  
      }
      else
      {
          BringWindowToTop(hWnd);
          ShowWindow(hWnd, SW_SHOW);
      }
  }
  </code></pre>
  
  <p>However both of the windows lose focus as soon as the threads detach.</p>
  
  <p>If I wait for the message queue to empty (Application.DoEvents()) and activate my window (which is now in foreground but not focused) it will regain the focus and keep it.</p>
  
  <p>If I do it before the message queue is empty it will lose focus again.</p>
  
  <p>So I would guess something of the detaching takes the focus from my windows but i have no idea what that is or how to prevent it.</p>
  
  <p>This is the first thing I do not quite understand.</p>
  
  <p>The second thing I do not get is, if I do not set my window to foreground:</p>
  
  <pre><code>AttachThreadInput(foregroundThread, appThread, true);
  
  AttachThreadInput(foregroundThread, appThread, false);
  Application.DoEvents();
  this.Activate();
  </code></pre>
  
  <p>wait for the message queue to empty, and activate my window (this time it is not in foreground and the other window still has the focus), it actually gets activated, even though the threads are not attached anymore.</p>
  
  <p>perhaps someone with a better understanding of AttachThreadInput can answer me these 2 questions.</p>
  
  <p><strong>INFO:</strong><br>
  I need to steal the focus in this case, because my app gets called via an API. The other app that calls mine, waits for feedback from my app and in most times freezes until it gets the info.</p>
  
  <p>In case the other app is Fullscreen many user do not notice the blinking in the taskbar and think the other app crashed and kill it with the Taskmamanger. Since i do not necessarily have control over the other app, i cannot tell it to set the focus to my window.</p>
  
  <p>This method won't get called if it is not absolutelly necessary, in this case this behavior, which is hostile, i know that, is as well wanted by myself as by the user.</p>