Skip to content

Instantly share code, notes, and snippets.

@caspark
Created May 28, 2020 03:12
Show Gist options
  • Save caspark/36b1f2b47e37735e323863b1dda7458f to your computer and use it in GitHub Desktop.
Save caspark/36b1f2b47e37735e323863b1dda7458f to your computer and use it in GitHub Desktop.
Python UI Automation text fetching from a Windows contro sample
import uiautomation as auto
# move mouse cursor over a text box with some text in it first
c = auto.ControlFromCursor()
v = c.GetValuePattern()
print(v.Value) # should print the contents of the text box
# now select some text in that same control
t = c.GetTextPattern()
sel = t.GetSelection()[0] # get the first selected range (I think the returned list is to support separate selection ranges)
sel.GetText() # should print out the selected text
# NB: not everything in TextRange is implemented correctly
# in particular, operations like ExpandToEnclosingUnit() don't have the right
# signature when you compare the python-uiautomation source with the docs for
# the native com API that Microsoft publishes
#
# also, there does not seem to be a way to get the position of the caret (which
# is what TextPattern#GetSelection does) in terms of "how many characters into
# the ValuePattern#Value" is it. Haven't found a workaround for that yet sadly.
@caspark
Copy link
Author

caspark commented Jun 7, 2020

Yep, the gist as written is what worked for accessing the edit control in Gitter - but it will depend on the app in question. A more robust version would find the control currently focused and look at that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment