title: How to retrieve the selected text from the active window
body: <p>I am trying to create a simple open source utility for windows using <strong>Python</strong> that can perform user-defined actions on the selected text of the currently active window. The utility should be activated using a pre-defined keyboard shortcut.</p>
  
  <p>Usage is partially outlined in the following example:</p>
  
  <ol>
  <li>The user selects some text using the mouse or the keyboard (in any application window)</li>
  <li>The user presses a pre-defined keyboard shortcut</li>
  <li>The selected text is retrieved by our utility or copied to clipboard (both approaches should be fine)</li>
  <li>The keyboard shortcut-dependent action is performed on the selected text</li>
  </ol>
  
  <p>What puzzles me is <strong>step 3</strong>. <em>How the selected text is retrieved from the active window</em>. This should work with all applications.</p>
  
  <p>I use the <strong>pywin32</strong> module.</p>
  
  <p>Thanks in advance for your answers and tips.</p>
  
  <p><strong>Update #1</strong>:</p>
  
  <p>Turns out that there are two approaches to accomplish the task:</p>
  
  <ol>
  <li>Find the active window, then send a message/keystroke (Ctrl-C) to it in order to copy the selected text to the clipboard. Then the utility can work on the text by accessing it using the clipboard-related functions.</li>
  <li>Find the active Window, then retrieve the selected text directly (without copying it to clipboard). This seems more difficult than the 1st approach.</li>
  </ol>
  
  <p>As starting points:</p>
  
  <p>Get the active window ID as Anurag Uniyal has pointed out in his <a href="https://stackoverflow.com/questions/1007185/how-to-retrieve-the-selected-text-from-the-active-window/1007553#1007553">reply</a>.</p>
  
  <p>Or get the window object with the following code:</p>
  
  <pre><code>import win32ui
  wnd = win32ui.GetForegroundWindow()
  print wnd.GetWindowText()
  </code></pre>