I converted my System.Windows.Automation code to the newer, faster IUIAutomation framework. I want to get the current selected text in any application (other app needs to support Automation of course). See the NEW Code below:
CUIAutomation _automation = new CUIAutomation(); var element = _automation.GetFocusedElement(); if (element != null) { IUIAutomationTextPattern textPattern = (IUIAutomationTextPattern) element.GetCurrentPattern(10014); if(textPattern != null) { var sb = new StringBuilder(); var range = textPattern.GetSelection(); sb.Append(range.GetElement(0).GetText(-1)); return sb.ToString(); } }
Weirdly, this code only works in Visual Studio itself and no other app where it should (Edge browser for example), but when I add (add the beginning of the
function) the following codepiece from the old System.Windows.Automation framework it suddenly works in expected apps (Edge browser for example).
var x = AutomationElement.FocusedElement;
There seems to be something broken in the IUIAutomation framework. Adding the old codepiece is not an option. It drastically slowes down the code. How can this be fixed?