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&gt;

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

Author
James Crowley

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: