Tuesday, 11 May 2010

Write lines to a RichTextBox control in different colours (VB .net example)

I create a lot of back end "processing" software, for example migration or upgrade tools that process documents as they find them on a server. As a standard, I tend to write their progress out to a text file, but I also like the program to show me what is happening as it processes files by writing the log file to the screen. This is particularly useful when debugging the application, but it's also far more satisfying to see something happening on the screen.

In this situation it is nice to write out warnings or non critical errors in different colours in order to attract the eye.

To achieve this, create a RichTextBox control on your main form (in my example it is called "fInfoBox"), and write to it using the code in the sub routine below.

Sub ShowLog(ByVal qFore as Drawing.Color, ByVal sMesg as string)
   Dim sDispMess As String
   sDispMess = Date.Now()& ": " & sMesg & vbCrLf 

   With fInfoBox 'This is the name of you RichTextBox control on your form
       .SelectionStart = Len(.Text)
       .SelectionBullet = True  ' This shows the line in bulleted form, comment out if not required

       .SelectionColor = qFore
       .SelectedText = sDispMess.ToString()
    End With

    fInfoBox.ScrollToCaret()  ' This scrols to the last line of the text box
End Sub

To display a message with a font colour of blue, call the routine like this:
ShowLog(Drawing.Color.Blue, "This message will appear in a font color of blue")
For a red message, try this:
ShowLog(Drawing.Color.Red, "ERROR: This message will display in a font color of red!!")
This is a very simple example, but I hope it helps someone get started with this sort of thing and gives you some ideas.

Remember that if you use threading or the backgroundworker class to remove your time consuming processes from the UI (which you should, especially since this is so easy after .Net 2.0), then you will need to use a callback technique for your worker thread to be able to talk to your UI thread.