title: Why is SetWindowPos failing to bring windows to the front of the z-order when I have UIAccess rights? (Windows 7)
body: <p>I am having trouble with SetWindowPos failing to bring windows of external processes to the top of the z-order reliably. I am able to bring windows to the front like:</p>
  
  <pre><code>     NativeMethods.SetWindowPos(hwnd, new IntPtr(-1), Left, Top, Width, Height, 0x10);
       NativeMethods.SetWindowPos(hwnd, new IntPtr(-2), Left, Top, Width, Height, 0x10);
  </code></pre>
  
  <p>It doesn't work 100% of the time though. After some reading, I found a few things.</p>
  
  <p>SetWindowPos documentation states:</p>
  
  <pre><code>    To use SetWindowPos to bring a window to the top, the process that owns the window must have SetForegroundWindow permission.
  </code></pre>
  
  <p>An article on MSDN then states</p>
  
  <pre><code>    A process that is started with UIAccess rights has the following abilities:
      * Set the foreground window.
  </code></pre>
  
  <p>AllowSetForeground mentions</p>
  
  <pre><code>    The calling process must already be able to set the foreground window
  </code></pre>
  
  <p>I have signed my .exe and enabled UIAccess so that I can set the foreground window like so in my manifest:</p>
  
  <pre><code>     &lt;requestedExecutionLevel  level="highestAvailable" uiAccess="true" /&gt;
  </code></pre>
  
  <p>My program starts and I get the UAC prompt asking for permission. I then test for UIAccess, admin rights, and TokenElevationType. The first 2 return true, and the 3rd returns TokenElevationTypeFull. I still run into the same problems though with my new code though.</p>
  
  <p>My code is:</p>
  
  <pre><code>    uint processid=0;
      NativeMethods.GetWindowThreadProcessId(hwnd, out processid);
      NativeMethods.AllowSetForegroundWindow((int)processid);
      NativeMethods.SetWindowPos(hwnd, IntPtr.Zero, Left, Top, Width, Height, 0x10);
      NativeMethods.RedrawWindow(hwnd, IntPtr.Zero, IntPtr.Zero, NativeMethods.RedrawWindowFlags.Erase | NativeMethods.RedrawWindowFlags.Invalidate | NativeMethods.RedrawWindowFlags.NoChildren);
      NativeMethods.RedrawWindow(hwnd, IntPtr.Zero, IntPtr.Zero, NativeMethods.RedrawWindowFlags.Erase | NativeMethods.RedrawWindowFlags.Invalidate | NativeMethods.RedrawWindowFlags.UpdateNow | NativeMethods.RedrawWindowFlags.AllChildren);
  </code></pre>