How to get selected text from ANY window (using user interface automation) - C #

I have a small tray application that registers a hotkey for the entire system. When a user selects text anywhere in any application and presses this hotkey, I want to be able to capture the selected text. I am currently doing this using AutomationElements:

//Using FocusedElement (since the focused element should be the control with the selected text?) AutomationElement ae = AutomationElement.FocusedElement; AutomationElement txtElement = ae.FindFirst(TreeScope.Subtree,Condition.TrueCondition); if(txtElement == null) return; TextPattern tp; try { tp = txtElement.GetCurrentPattern(TextPattern.Pattern) as TextPattern; } catch(Exception ex) { return; } TextPatternRange[] trs; if (tp.SupportedTextSelection == SupportedTextSelection.None) { return; } else { trs = tp.GetSelection(); string selectedText = trs[0].GetText(-1); MessageBox.Show(selectedText ); } 

This works for some applications (such as notepads, visual studio editing windows, etc.), but not for all (e.g. Word, FireFox, Chrome, etc.)

Anyone here with any ideas on how to be able to pull out the selected text in ANY program?

+7
c # automation ui-automation
source share
3 answers

Unfortunately, there is no way to get selected text from any arbitrary application. UI Automation works if the application supports UIA TextPattern; Unfortunately, most are not. I wrote an application that tried to do this and had a bunch of backups.

I tried (in order):

  • UIA.TextPattern
  • Internet Explorer specification (this one had different implementations for IE 6,7,8,9).
  • Specific to Adobe Reader
  • Clipboard

This covered 80-90% of applications, but there were many that still failed.

Note that clipboard recovery has its problems; some applications (Office, etc.) place information about a particular provider on the clipboard, which may have pointers to internal data; when you put your own information on the clipboard, the internal data is freed, and when you put the old data, the clipboard now indicates the freed data, which leads to crashes. You can get around this a bit by only saving / restoring known clipboard formats, but again, this leads to an odd behavior in which applications behave “incorrectly” rather than crashing.

+7
source share

Can I look at the clipboard and make my own hotkey: CTRL + C?

You will not be able to read the selected text from any application. For example, some PDF files protect content that prohibits copying.

+1
source share

UIA technology is not supported by all applications, you can try to use MSAA in some cases (for example, FF, Chrome, etc.), but you still get a lot of problems. The best way is to save the current clipboard text, send a “CTRL + C” message using the SendMessage WinAPI function, get the clipboard text and restore the clipboard to the original, as Rick said.

+1
source share

All Articles