title: GetFocus - Win32api help
body: <p>i am trying to grab the selected text from the open form on a users machine. Currently i have tried using <code>GetFocus</code> which is defined as</p>
  
  <pre><code>    '[DllImport("user32.dll")]
      static extern int GetFocus();'
  </code></pre>
  
  <p>In the api it says - <code>Retrieves the handle to the window that has the keyboard focus, if the window is attached to the calling thread's message queue.</code> Which explains why my app can grab the selected text from a window thats part of my app, but not one thats external, like a pdf for example.</p>
  
  <p>What alternative win32 method is available for me to use that would fit this purpose?</p>
  
  <p>Thanks.</p>
  
  <p>edit: this is the attempt at the moment </p>
  
  <p>[DllImport("user32.dll")]
      static extern int GetFocus();</p>
  
  <pre><code>[DllImport("user32.dll")]
  static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  
  [DllImport("kernel32.dll")]
  static extern uint GetCurrentThreadId();
  
  [DllImport("user32.dll")]
  static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);
  
  [DllImport("user32.dll")]
  static extern int GetForegroundWindow();
  
  [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
  static extern int SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam);
  
  
  // second overload of SendMessage
  
  [DllImport("user32.dll")]
  private static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam);
  
  const int WM_SETTEXT = 12;
  const int WM_GETTEXT = 13;
  
  private static string PerformCopy()
  {
      try
      {
          //Wait 5 seconds to give us a chance to give focus to some edit window,
          //notepad for example
          System.Threading.Thread.Sleep(1000);
          StringBuilder builder = new StringBuilder(500);
  
          int foregroundWindowHandle = GetForegroundWindow();
          uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0);
          uint currentThreadId = GetCurrentThreadId();
  
          //AttachTrheadInput is needed so we can get the handle of a focused window in another app
          AttachThreadInput(remoteThreadId, currentThreadId, true);
          //Get the handle of a focused window
  
  
          int focused = GetFocus();
  
  
  
  
          //Now detach since we got the focused handle
          AttachThreadInput(remoteThreadId, currentThreadId, false);
  
          //Get the text from the active window into the stringbuilder
          SendMessage(focused, WM_GETTEXT, builder.Capacity, builder);
  
          return builder.ToString();
      }
      catch (System.Exception oException)
      {
          throw oException;
      }
  }
  </code></pre>