WinAPI: Getting text selection of active window without using the clipboard
Asked Answered
G

1

2

I know that you can get the text selection by sending a WM_COPY message and then reading the new contents of the clipboard.
But how does Windows retrieve the text selection in the first place before it gets stored in the clipboard? I mean there has to be a way to get the text without sending it to the clipboard, right?
But all I could find online were workarounds that write to the clipboard and then quickly restore the old contents.. That's not what I'm looking for, though.

(This question is not about a specific programming language.)

Goar answered 18/3, 2016 at 11:59 Comment(1)
The official, documented and supported API to use in scenarios like these is UI Automation.Blayne
T
2

Just send EM_GETSEL to the control and then use GetWindowText to obtain the full control text and extract just the selection.

As you may have guessed this is not as efficient as WM_COPY.
This is because Edit controls are not meant to deal with huge texts, for that (and other purpose) there is the RichEditText control.

It allows you to do some efficient copy by either using:

  1. EM_GETSELTEXT to obtain only the selected text. You still need to know how much space to allocate: this is trivial with the EM_GETSEL or EM_EXGELSEL.

  2. Using EM_GETSEL (or equivalent) and then streaming the text with EM_STREAMOUT.

Needless to say, all of this is accomplished with a single API SendMessage which, if not already, you have to became confident with.

Tuberculosis answered 18/3, 2016 at 12:23 Comment(4)
"As you may have guessed this is not as efficient as WM_COPY" - Do you have any reference to back that statement? Why would opening the clipboard, copying data to global memory, and cleaning up (in addition to retrieving the control contents) be any more efficient than retrieving the control contents?Blayne
So I have to find out what kind of control I'm dealing with and then I need to find out what's the appropriate message to send? What about custom controls can they be accessed the same way? How does Windows determine which message to send etc?Goar
@Forivin: See my comment to your answer. It's your only option when dealing with custom controls, or windowless controls (very common for Qt applications, for example).Blayne
@Blayne You cannot extract just the selected text; you have to extract all the text from the control and than "substring" it. The VM_COPY is processed by the control itself, so it can copy only the selected text. It is faster if you extract small text, my point was that it doesn't scale.Tuberculosis

© 2022 - 2024 — McMap. All rights reserved.