Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving Selected Text from Webbrowser control in .net(C#)

I've been trying to figure out how to retrieve the text selected by the user in my webbrowser control and have had no luck after digging through msdn and other resources, So I was wondering if there is a way to actually do this. Maybe I simply missed something.

I appreciate any help or resources regarding this.

Thanks

like image 452
Cliff Avatar asked Oct 20 '08 02:10

Cliff


2 Answers

You need to use the Document.DomDocument property of the WebBrowser control and cast this to the IHtmlDocument2 interface provided in the Microsoft.mshtml interop assembly. This gives you access to the full DOM as is available to Javascript actually running in IE.

To do this you first need to add a reference to your project to the Microsoft.mshtml assembly normally at "C:\Program Files\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll". There may be more than one, make sure you choose the reference with this path.

Then to get the current text selection, for example:

using mshtml;

...

    IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2;

    IHTMLSelectionObject currentSelection= htmlDocument.selection;

    if (currentSelection!=null) 
    {
        IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange;

        if (range != null)
        {
            MessageBox.Show(range.text);
        }
    }

For more information on accessing the full DOM from a .NET application, see:

  • Walkthrough: Accessing the DHTML DOM from C#

  • IHTMLDocument2 Interface reference

like image 186
Ash Avatar answered Nov 01 '22 07:11

Ash


Just in case anybody is interested in solution that doesn't require adding a reference to mshtml.dll:

private string GetSelectedText()
{
    dynamic document = webBrowser.Document.DomDocument;
    dynamic selection = document.selection;
    dynamic text = selection.createRange().text;
    return (string)text;
}
like image 41
username Avatar answered Nov 01 '22 08:11

username