title: User32.DLL SetFocus fails with Win32 error 5:Access is denied
body: <p>The code below does the following</p>
  
  <p>PushWindowToFront():</p>
  
  <ul>
  <li>gets the current process id for reference later</li>
  <li>calls user32.dll function <strong>EnumWindows</strong> with callback <strong>EnumWindowsCallback</strong> method</li>
  <li>EnumWindows then iterates through each window and calls callback for each</li>
  </ul>
  
  <p>Callback:</p>
  
  <ul>
  <li>Check if window thread process id is same as current process id</li>
  <li>if so, check if Window text begins "Select "</li>
  <li>if so, call user32.dll function SetFocus on window handle</li>
  <li>check &amp; print last win32 error</li>
  </ul>
  
  <p>However, it always returns win32 error 5 - "Access is denied". Why wouldn't the application have access to call this function against a window belonging to the same process?</p>
  
  <p>.</p>
  
  <pre><code>    public void PushWindowToFront()
      {
          currentProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;
  
          Win32Methods.EnumWindowsCallbackDelegate callback = new Win32Methods.EnumWindowsCallbackDelegate(this.EnumWindowsCallback);
  
          Win32Methods.EnumWindows(callback, (IntPtr) 0);
      }
  
      public bool EnumWindowsCallback(IntPtr hWnd, IntPtr lParam)
      {
          uint i = 0;
  
          Win32Methods.GetWindowThreadProcessId(hWnd, out i);
  
          if (currentProcessId == i)
          {
  
              StringBuilder sb = new StringBuilder(512);
  
              Win32Methods.GetWindowText(hWnd, sb, sb.Capacity);
  
              if (sb.ToString().Split(' ')[0].ToLower().Equals("select"))
              {
                  IntPtr result = Win32Methods.SetFocus(hWnd);
                  Console.WriteLine("Window found: {0}\r\nSetting focus...\r\nResult: {1}\r\nLastError: {2}",
                      sb.ToString(), result, Marshal.GetLastWin32Error().ToString());
              }
          }
  
          return true;
      }
  </code></pre>