Library code snippets

Colour HTML Tags

This example colours the HTML tags in a RichTextBox. For this to work you need to add two RichText Boxes to a form, one named rchVisible and one named rchHidden (this richtextbox should have its visible property set to false).

Next, add the code below to your form. Don't forget to change the Open App.Path & " odbooks.htm" For Input As fnum line to point to a HTML file on your hard disk.

' Color the tags in the RichTextBox's text.
' This version is a little simple and does not
' ignores comment properly. It cannot handle nested
' brackets as in:
'
' <A HREF= <!-- here's a comment -->
'    http://www.vb-helper.com>
'
Private Sub ColorTags(rch As RichTextBox)
Dim txt As String
Dim tag_open As Integer
Dim tag_close As Integer

    txt = rch.Text
    tag_close = 1
    Do
        ' See where the next tag starts.
        tag_open = InStr(tag_close, txt, "<")
        If tag_open = 0 Then Exit Do
       
        ' See where the tag ends.
        tag_close = InStr(tag_open, txt, ">")
        If tag_open = 0 Then tag_close = Len(txt)
       
        ' Color the tag.
        rch.SelStart = tag_open - 1
        rch.SelLength = tag_close - tag_open + 1
        rch.SelColor = vbRed
    Loop
End Sub

' Load the file.
Private Sub Form_Load()
Dim fnum As Integer
Dim txt As String

    ' Move the hidden text box so it cannot be seen.
    rchHidden.Move -rchHidden.Width - 120, 0
   
    ' Load the file.
    fnum = FreeFile
    Open App.Path & " odbooks.htm" For Input As fnum
    txt = Input$(LOF(fnum), fnum)
    rchHidden.Text = txt
    Close fnum

    ' Color the HTML tags.
    ColorTags rchHidden

    ' Copy the result to the visible text box.
    rchHidden.SelStart = 0
    rchHidden.SelLength = Len(rchHidden.Text)
    rchVisible.SelStart = 0
    rchVisible.SelLength = Len(rchVisible.Text)
    rchVisible.SelRTF = rchHidden.SelRTF
End Sub
Private Sub Form_Resize()
    rchVisible.Move 0, 0, ScaleWidth, ScaleHeight
End Sub

Comments

  1. 08 Sep 2002 at 05:33

    You need to be using a RichTextBox; to do this go to project|components and check the 'Microsoft RichTextBox' component.

  2. 07 Sep 2002 at 18:17

    I can't get this to work.  I have tried over and over and it keeps saying "Compile error: User Defined Type Not Defined".


    It then highlites "Private Sub ColorTags(rch As RichTextBox)"


    Anyone have any ideas?


    Thanks,
    Joel Strellner

  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Colour HTML Tags.

Leave a comment

Sign in or Join us (it's free).