Copy text from WebBrowser control and Paste in RichTextBox with format using VB.Net in Windows Application

Last Reply 5 months ago By dnnyobi

Posted 5 months ago

How to pass or copy text from a webbrowser control to richtextbox without losing format

I want to pass text from webbrowser control to a richtextbox on button click without any loss of format. I.e. bold, italic, underline etc.

Please note that it is for windows application.

I used the code below to enable me type directly on WebBrowser control on form load. And also edit any text I type on it using Bold, Italic, Color, align, line spacing codes etc. I only stated the code I used for bold here as reference.

Private _htmlDoc As MSHTML.IHTMLDocument2 = Nothing
Private Sub _initHtmlEditor()
    _htmlDoc = TryCast(WebBrowser1.Document.DomDocument, MSHTML.IHTMLDocument2)
    _htmlDoc.designMode = "on"
End Sub 
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    _htmlDoc.execCommand("Bold", False, Nothing)'Bolden
End Sub

I am using the code below to copy and paste into the RichTextBox control. 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    WebBrowser1.Document.ExecCommand("SelectAll", False, vbNull)
    WebBrowser1.Document.ExecCommand("Copy", False, vbNull)
End Sub

The problem I have here is Line Spacing and text Alignment which do not apply when I copy and paste.

Posted 5 months ago

I was able to figure it out with the following Function code

    Private Shared Function ExtractHtmlFromClipboardData(ByVal htmlDataString As String, <Out> ByRef result As String) As Boolean
        result = ""
        Dim startHtmlIndex As Integer = htmlDataString.IndexOf("StartHTML:")

        If startHtmlIndex < 0 Then
            Return False
        End If

        startHtmlIndex = Integer.Parse(htmlDataString.Substring(startHtmlIndex + "StartHTML:".Length, "0123456789".Length))

        If startHtmlIndex < 0 OrElse startHtmlIndex > htmlDataString.Length Then
            Return False
        End If

        Dim endHtmlIndex As Integer = htmlDataString.IndexOf("EndHTML:")

        If endHtmlIndex < 0 Then
            Return False
        End If

        endHtmlIndex = Integer.Parse(htmlDataString.Substring(endHtmlIndex + "EndHTML:".Length, "0123456789".Length))

        If endHtmlIndex > htmlDataString.Length Then
            endHtmlIndex = htmlDataString.Length
        End If

        result = htmlDataString.Substring(startHtmlIndex, endHtmlIndex - startHtmlIndex)
        Return True
    End Function

Thank you for your effort.