title: Capture Highlighted Text from any window using C#
body: <p>How to read the highlighted/Selected Text from any window using c#.</p>
  
  <p>i tried 2 approaches.</p>
  
  <ol>
  <li>Send "^c" whenever user selects some thing. But in this case my clipboard is flooded with lots of unnecessary data. Sometime it copied passwords also.</li>
  </ol>
  
  <p>so i switched my approach to 2nd method, send message method.</p>
  
  <p>see this sample code</p>
  
  <pre><code> [DllImport("user32.dll")]
      static extern int GetFocus();
  
      [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 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(5000);
              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>
  
  <p>this code working fine in Notepad. But if i try to capture from another applications like Mozilla firefox, or Visual Studio IDE, it's not returning the text.</p>
  
  <p>Can anybody please help me, where i am doing wrong? First of all, i have chosen the right approach?</p>