我有一个小托盘应用程序,它注册了一个系统范围的热键。当用户在任何应用程序中的任意位置选择文本并按下此热键时,我希望能够捕获所选文本。我目前正在使用 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 );
}
这适用于某些应用程序(例如记事本、Visual Studio 编辑框等),但不适用于所有应用程序(例如 Word、FireFox、Chrome 等)。
这里有人对如何能够在任何应用程序中检索所选文本有任何想法吗?