Get the selected text from a WebBrowser control (WinForms)


There are two methods that I know of to get the selected text from a WebBrowser control, each with a pro and con. The first method is to import the mshtml.dll library into your project and use it to grab the selected text off of the browser. Note, this method does return you text like “Copy” would. Copying to the clipboard from the browser is running additional logic that formats some of the text selected.

''' <summary>
''' Returns the selected text from a WebBrowser control.
''' </summary>
''' <param name="wb"></param>
Public Function GetWebBrowserSelectedText(ByVal wb As WebBrowser) As String
    Dim htmlDocument As mshtml.IHTMLDocument2 = TryCast(WebBrowser1.Document.DomDocument, mshtml.IHTMLDocument2)
    Dim currentSelection As mshtml.IHTMLSelectionObject = htmlDocument.selection

    If currentSelection IsNot Nothing Then
        Dim range As mshtml.IHTMLTxtRange = TryCast(currentSelection.createRange(), mshtml.IHTMLTxtRange)
        If range IsNot Nothing Then
            Return range.text
        End If
    End If

    Return ""
End Function

Now, sometimes, you want the text as the browser would copy it. To do this, we need to invoke the copy method from the browser. The one problem with this thought is that it will overwrite the users clipboard which isn’t usually a desirable way to do this (you could get around this by saving the previous clipboard entry and resetting it which will work but is a little hacky). Here an extension method off of the WebBrowser control that will allow you to copy text:

''' <summary>
''' Copys the current selected text from the HtmlDocument and puts it on the clipboard.
''' </summary>
''' <param name="wb"></param>
<Extension()> _
Public Sub Copy(ByVal wb As WebBrowser)
    wb.Document.ExecCommand("Copy", False, "")
End Sub

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.