Unfortunately, there's no way to get the selected text from any arbitrary application. UI Automation works if the application supports UIA TextPattern; unfortunately, most do not. I wrote an application that tried to do this, and had a bunch of fallbacks.
I tried (pretty much in order):
- UIA.TextPattern
- Internet Explorer-specific (this had different implementations for IE 6,7,8,9)
- Adobe Reader-specific
- Clipboard
This covered 80-90% of the applications out there, but there were quite a few that still failed.
Note that restoring the clipboard has problems of its own; some applications (Office, etc.) put vendor-specific information into the clipboard that can have pointers into internal data; when you put your own info on the clipboard, the internal data gets released, and when you put the old data back, the clipboard now points to freed data, resulting in crashes. You could work around this somewhat by only saving/restoring known clipboard formats, but again, that results in odd behavior in that apps behave "wrong" instead of crashing.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…