How to retrieve the selected text from the active window

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:

  1. The user selects some text using the mouse or the keyboard (in any application window)
  2. The user presses a pre-defined keyboard shortcut
  3. The selected text is retrieved by our utility or copied to clipboard (both approaches should be fine)
  4. 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:

  1. 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.
  2. 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()


Asked by: Blake477 | Posted: 30-11-2021






Answer 1

the code below will work only on simple text boxes (just did it in VB6, and ported to python)

edit: it was tested only on python 2.6

from ctypes import *
import win32gui
import win32api
import win32con


user32 = windll.user32
kernel32 = windll.kernel32

class RECT(Structure):
 _fields_ = [
     ("left", c_ulong),
     ("top", c_ulong),
     ("right", c_ulong),
     ("bottom", c_ulong)
 ]

class GUITHREADINFO(Structure):
 _fields_ = [
     ("cbSize", c_ulong),
     ("flags", c_ulong),
     ("hwndActive", c_ulong),
     ("hwndFocus", c_ulong),
     ("hwndCapture", c_ulong),
     ("hwndMenuOwner", c_ulong),
     ("hwndMoveSize", c_ulong),
     ("hwndCaret", c_ulong),
     ("rcCaret", RECT)
 ]



def get_selected_text_from_front_window(): # As String
    ''' vb6 to python translation '''

    gui = GUITHREADINFO(cbSize=sizeof(GUITHREADINFO))
    txt=''
    ast_Clipboard_Obj=None
    Last_Clipboard_Temp = -1


    user32.GetGUIThreadInfo(0, byref(gui))

    txt = GetCaretWindowText(gui.hwndCaret, True)

    '''
    if Txt = "" Then
        LastClipboardClip = ""
        Last_Clipboard_Obj = GetClipboard
        Last_Clipboard_Temp = LastClipboardFormat
        SendKeys "^(c)"
        GetClipboard
        Txt = LastClipboardClip
        if LastClipboardClip <> "" Then Txt = LastClipboardClip
        RestoreClipboard Last_Clipboard_Obj, Last_Clipboard_Temp
        print "clbrd: " + Txt
    End If
    '''    
    return txt



def GetCaretWindowText(hWndCaret, Selected = False): # As String

    startpos =0
    endpos =0

    txt = ""

    if hWndCaret:

        buf_size = 1 + win32gui.SendMessage(hWndCaret, win32con.WM_GETTEXTLENGTH, 0, 0)
        if buf_size:
            buffer = win32gui.PyMakeBuffer(buf_size)
            win32gui.SendMessage(hWndCaret, win32con.WM_GETTEXT, buf_size, buffer)
            txt = buffer[:buf_size]

        if Selected and buf_size:
            selinfo  = win32gui.SendMessage(hWndCaret, win32con.EM_GETSEL, 0, 0)
            endpos   = win32api.HIWORD(selinfo)
            startpos = win32api.LOWORD(selinfo)
            return txt[startpos: endpos]

    return txt

if __name__ == '__main__':
    print get_selected_text_from_front_window()

Answered by: Dainton770 | Posted: 01-01-2022



Answer 2

You're far better off using the Ctrl-C method. Fetching text directly will work for something like an edit control, but is useless for retrieving text that an application has painted directly on its own window.

Answered by: Dexter243 | Posted: 01-01-2022



Answer 3

It won't be trivial but here is the starting point

import win32gui
hwnd = win32gui.GetForegroundWindow()
print win32gui.GetWindowText(hwnd)

Maybe you will have to use FindWindow,FindWindowEx to get child windows with focus

edit: also while experimenting use spy++ to see how it retrieves information about various windows, see hwnd, window class etc

basically if you can find a example in C/C++/C# it won't be difficult to translate that into pywin32 equivalent, so in a way it is win32 api specific question

Answered by: Brad246 | Posted: 01-01-2022



Answer 4

It appears that while the clipboard and associated copy and paste shortcuts are ubiquitous, they must be added to applications by developers. The best bet is to use a listener to capture when ctrl+c is activated, check that the clipboard is not in use and has data on it, and then manipulate the data from there.
You can check out Microsoft's dev page here:

https://docs.microsoft.com/en-us/windows/win32/dataxchg/using-the-clipboard#implementing-the-cut-copy-and-paste-commands

Answered by: Chester306 | Posted: 01-01-2022



Similar questions

python - Retrieve the selected record

I have a QTableWidget with 9 columns and X rows. When I double-click a cell it displays its contents. How should I change the code to view, with a double-click, the entire row, i.e. the whole record? class Searchtable(QTableWidget): def __init__(self): super().__init__() self.tab = QTableWidget(0,9,self) self.tab.setColumnWidth(8,130) self.tab.setColumnWidth(7,70) ...


python - Django query to retrieve items that are selected as foreign keys?

So, imagine there is a model City which has a foreign key Country. In the database, some Countries were selected in one or more cities, and some in none. How can we find only those countries that are selected in one or more cities, excluding those that aren't selected at all?


c# - How to retrieve only a selected portion of online resource

Is it possible to retrieve only a selected portion of specified URL in C#/python or any other, to reduce network traffic. For Example: I want to scrape a website and have lets say a thousand urls to process but I only need a small portion of the web page (skip to 100 and download next 200 bytes).


python - Retrieve the selected record

I have a QTableWidget with 9 columns and X rows. When I double-click a cell it displays its contents. How should I change the code to view, with a double-click, the entire row, i.e. the whole record? class Searchtable(QTableWidget): def __init__(self): super().__init__() self.tab = QTableWidget(0,9,self) self.tab.setColumnWidth(8,130) self.tab.setColumnWidth(7,70) ...


python - Django - Retrieve or get data from selected foreign key field

Relatively new to Django, I'm working on a Django project and attempting to retrieve particular foreign key object into variable when it's selected in Form. model.py class item_category(models.Model): idItemCat = models.CharField(primary_key=True max_length=5) nameCategory = models.CharField(max_length=150) def __str__(self): return self.nameCategory class item_code(...


python - retrieve selected value from a binded combobox in tkinter

I am trying to retrieve the selected value from a binded combobox. In the below code, I have binded the combobox named “LSF_Combo” to another combobox “Queue _Combo” . I am trying to retrieve the selected value from the “Queue_Combo”, using Queue_Combo.get() method, but I am not able to do so, since its scope is limited within LSF_fields_Enable(event) inner function. I am able to retrieve ...


html - How can I retrieve the page title of a webpage using Python?

How can I retrieve the page title of a webpage (title html tag) using Python?


python - How to retrieve an element from a set without removing it?

Suppose the following: &gt;&gt;&gt; s = set([1, 2, 3]) How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host. Quick and dirty: &gt;&gt;&gt; elem = s.pop() &gt;&gt;&gt; s.add(elem)


sql server - Python: Retrieve Image from MSSQL

I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image! The following is my code: #!/usr/bin/python import _mssql mssql=_mssql.connect('&lt;ServerIP&gt;','&lt;UserID&gt;','&lt;Password&gt;') mssql.select_db('&lt;Database...


python - Best way to retrieve variable values from a text file?

Referring on this question, I have a similar -but not the same- problem.. On my way, I'll have some text file, structured like: var_a: 'home' var_b: 'car' var_c: 15.5 And I need that python read the file and then create a variable named var_a with value 'home', and so on. Example...


python - How can I retrieve last x elements in Django

I am trying to retrieve the latest 5 posts (by post time) In the views.py, if I try blog_post_list = blogPosts.objects.all()[:5] It retreives the first 5 elements of the blogPosts objects, how can I reverse this to retreive the latest ones? Cheers


python - Retrieve module object from stack frame

Given a frame object, I need to get the corresponding module object. In other words, implement callers_module so this works: import sys from some_other_module import callers_module assert sys.modules[__name__] is callers_module() (That would be equivalent because I can generate a stack trace in the function for this test case. The imports are there simply to make that example complete an...


How do I retrieve Hotmail contacts with python

How can I retrieve contacts from hotmail with python? Is there any example?


linux - How to retrieve the process start time (or uptime) in python

How to retrieve the process start time (or uptime) in python in Linux? I only know, I can call "ps -p my_process_id -f" and then parse the output. But it is not cool.


python - Retrieve the two highest item from a list containing 100,000 integers

How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?


c++ - How do I retrieve program output in Python?

I'm not a Perl user, but from this question deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to: $version = `java -version`; How would I go about getting the same end result in Python? Does t...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top