开发者

Get highlighted text from active window

开发者 https://www.devze.com 2022-12-16 11:40 出处:网络
I would like to know how can I get h开发者_运维技巧ighlighted text from any window for example: (excel, ie, firefox,…).

I would like to know how can I get h开发者_运维技巧ighlighted text from any window for example: (excel, ie, firefox,…). please note that the following message not work in the above application WM_GETTEXT,WM_COPY,EM_GETSELTEXT.

I have also tried control C (copy) and get selected text from clipboard but it is not a good idea.

Language used: C#


I haven't tried it myself, but the Microsoft UI Automation API should have the functionality that you need.

The UI Automation API is what you would use if you were building a screen reader to assist blind people. So it should definitely be able to access the selected text in an arbitrary application.

A good place to start would be with the "Text Pattern Overview" at http://msdn.microsoft.com/en-us/library/ms745158.aspx

Also keep your eye on question 517694. I think you'll find that answers to that question will solve your problem.


No answers huh? Well, I know you can get it from Excel, Word etc using interop. Look into that. It might give you som ideas on how to proceed with ie and ff. But basically the recieving application must have some sort of fascility for letting you do this and I don't think there's any general way which works all the time.


There is no general purpose answer to this question. Each window class will have a different solution.

For instance, if the hilighted text is in an edit window, then you can use EM_GETSEL to get the range of the selection, then WM_GETTEXT to get the text (and then throw the unselected part a way) or EM_LINEFROMCHAR to turn that range into line indexes, and then EM_GETLINE to get the selected text one line at a time.

But this won't work for any other window class.


No need to write this in C# from scratch. What's wrong with using the clipboard? This script ensures that it restores what was on the clipboard when it has finished.

Autohotkey makes this much simpler.

; Hotkey:  Ctrl Shift t

^!t::

; Remember what was in the clipboard
clipboardPrev = %clipboard%

; Clear the clipboard
clipboard:=

Sleep,200

; Send a Ctrl C to copy the current selection
SendInput, {Ctrl down}c{Ctrl up}

Sleep,200

; Get the current selection from the clipboard
selectedText=%Clipboard%

if SelectedText =
{
    ; If the first attempt didn't get any test, try again
    Sleep,200

    ; Send a Ctrl C to copy the current selection
    SendInput, {Ctrl down}c{Ctrl up}

    ; Get the current selection from the clipboard
    selectedText=%Clipboard%

}

; Restore the clipboard
clipboard=%clipboardPrev% 

MsgBox, %selectedText%

return
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号