I would like to get the word that a user has clicked on in a FlowDocument.
I am currently adding an event handler to every Run in the document and iterating through the TextPointers in the Run that was clicked, calling GetCharacterRect() on each one and checking if the rectangle contains the point.
However, when the click occurs near the end of a long Run this takes > 10 seconds.
Is there any more efficient method?
I’d say the easiest way is to use the Automation interfaces:
The ITextProvider usage requires a reference to the UIAutomationProvider assembly. This assembly is not commonly referenced, so you may need to add it. UIAutomationTypes will also be needed to use some of its methods.
Note that there are many options for creating your automation peer depending on how you are presenting the FlowDocument:
Update
I tried this and it works well, though converting from an ITextRangeProvider to a TextPointer proved more difficult than I expected.
I packaged the algorithm in an extension method
ScreenPointToTextPointerfor easy use. Here is an example of how my extension method can be used to bold all text before the mouse pointer and un-bold all text after it:Here is the code for the extension method:
Also note the use of PointToScreen in the example MouseMove method to get a screen point to pass into the extension method.