如何从任何窗口中选择文本(使用UI自动化) - C#文本、窗口中、UI

2023-09-02 10:51:26 作者:外面风大跟我回家

我有一个小托盘应用程序,它注册一个全系统的热键。当用户在任何应用程序和presses任何地方选择一个文本此热键,我希望能够捕捉到选定的文本。目前,我正在做这个使用AutomationElements:

I have a small tray application which registers a system-wide hotkey. When the user selects a text anywhere in any application and presses this hotkey I want to be able to capture the selected text. I'm 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 );

}

这适用于某些应用程序(如记事本,视觉工作室编辑框等),但不是所有的(如Word,火狐,Chrome,等等。)

This works for some apps (such as notepad, visual studios edit boxes and such) but not for all (such as Word, FireFox, Chrome, and so on.)

这里有人有任何想法如何能够中检索在任何应用程序选定的文本?

Anyone here with any ideas of how to be able to retreive the selected text in ANY application?

推荐答案

不幸的是,有没有办法让从任意应用程序选定的文本。 UI自动化工程如果应用程序支持UIA Textpattern的;不幸的是,大多数人没有。我写道,试图做到这一点的应用程序,并且有一帮回退的。

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.

我试过(pretty的多少按顺序):

I tried (pretty much in order):

UIA.TextPattern 在Internet Explorer中特定的(这有不同的实现IE 6,7,8,9) 在Adobe Reader的专用 在剪贴板

这涵盖了应用程序在那里的80-90%,但也有不少仍然失败了。

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.