views:

121

answers:

1

I'm creating a IE browser plug-in that needs to be kept updated about what text has been selected by the user, or if no text is currently selected at all. I learned how to get the selected text by reading here. This is my code for doing so:

var doc = browser.Document as IHTMLDocument2;
var selection = doc.selection as IHTMLSelectionObject;
var range = selection.createRange() as IHTMLTxtRange;
string selectedText = range.text;

However, I am having difficulty determining the event handler(s) from which to access range.text to update my plug-in. Using the selectionchange event alone does not work in all cases. When the user deselects the text by clicking directly on the selection, as opposed to clicking on a different part of the webpage, range.text still contains the old (non-null) value when selectionchange is raised. A workaround is to also listen for click events. A click event is raised immediately after selectionchange, but at which point range.text is finally null. However, I've encountered a further problem for which I haven't found a solution. That is, if a user double-clicks on a word, thus selecting it, the selectionchange event isn't raised at all. Plus, when the click event (or mousedown event or selectstart event) is raised, range.text is still null!

How can I solve this latter problem? Or is there an overall better approach I can take?

+1  A: 

Try to use the ondragend event for the simple selection and the ondblclick event for the double click selection. If it doesn't work try to combine some events (http://javascript.gakaa.com/c/events.aspx)

mck89
Using the dblclick event solved the problem for single-word double click selection. Thanks for pointing that event out - I didn't notice it probably due to the missing vowels. Someone's keyboard at Microsoft was apparently broken. As for the ondragend event, it isn't actually applicable since drag selection isn't a DnD operation. So now in my program, I just route all three events - selectionchange, click, and dblclick - to the same handler which saves the value of range.text.
HappyNomad