I am trying to create a simple open source utility for windows using Python 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.
Usage is partially outlined in the following example:
- The user selects some text using the mouse or the keyboard (in any application window)
- The user presses a pre-defined keyboard shortcut
- The selected text is retrieved by our utility or copied to clipboard (both approaches should be fine)
- The keyboard shortcut-dependent action is performed on the selected text
What puzzles me is step 3. How the selected text is retrieved from the active window. This should work with all applications.
I use the pywin32 module.
Thanks in advance for your answers and tips.
Update #1:
Turns out that there are two approaches to accomplish the task:
- 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.
- Find the active Window, then retrieve the selected text directly (without copying it to clipboard). This seems more difficult than the 1st approach.
As starting points:
Get the active window ID as Anurag Uniyal has pointed out in his reply.
Or get the window object with the following code:
import win32ui
wnd = win32ui.GetForegroundWindow()
print wnd.GetWindowText()