Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Append Multiple Colored Texts to a RichTextBox using VB.NET

1.80/5 (2 votes)
25 Feb 2019CPOL2 min read 14.7K  
This is an alternative for Multiple Colored Texts in RichTextBox using C#
This VB.NET code provides a subroutine, appendColoredTextToRichTextBox, allowing the appending of colored text to a RichTextBox in a Windows Forms application. The code includes two versions (2019 and 2024) with XML comments explaining the usage.

Introduction

This VB.NET code snippet for Windows Forms can append colored text to a richtextbox.
Each appended text gets its own color.

I tested the new version of 2024 and the old version of 2019 with good results on VS2022.

Background

I used the multiple colored text box in my application checkFreeSpace that I wrote for checking the free space on one of my disks for bad sectors.

I wanted to append several red messages intertwined with black comment texts into a richtextbox.
By following the original article for C#, I found how to do this.

Using the Code

The XML comments of both subroutines appendColoredTextToRichTextBox tell how to use them.

VB.NET
#Region "Colored Texts to a RichTextBox"
     ''' <summary>
    ''' Appends colored text to a rich text box. This is the version of 2024.
    ''' This subroutine is new on January 22 2024.
    ''' This subroutine will most probably function from VS2013 through VS2022.
    ''' </summary>
    ''' <param name="appendBox">
    ''' The rich text box to append to.
    ''' </param>
    ''' <param name="inText">
    ''' The text to append.
    ''' </param>
    ''' <param name="inForeColor">
    ''' The color to display the appended text in.
    ''' The default color is the current forecolor.
    ''' </param>
    ''' <param name="inBackColor">
    ''' The color to display the background of the appended text in.
    ''' The default color is the current backcolor.
    ''' </param>
    ''' <param name="insertNewLine">
    ''' True means a new line is to be inserted before appending the new text.
    ''' </param>
    ''' <param name="appendBoxFont">
    ''' If missing, the current font will be used.
    ''' Else the given font will be used.
    ''' </param>
    ''' <param name="suspendLayout">
    ''' True, which is the default,
    ''' means that applying the new layout of the richtextbox will get cached.
    ''' </param>
    ''' <param name="updateViewNow">
    ''' True means the appended text is to be seen as soon as possible.
    ''' </param>
    ''' <remarks>
    ''' Language: VB.NET VS2022, January 22 2024, EAHMK.
    ''' The original C# solution stems from Multiple Colored Texts in RichTextBox
    ''' using C# by S.Vinothkumar, 27 Jun 2009.
    ''' </remarks>
    Public Sub appendColoredTextToRichTextBox(
        appendBox As Windows.Forms.RichTextBox,
        inText As String,
        Optional inForeColor As Drawing.Color = Nothing,
        Optional inBackColor As Drawing.Color = Nothing,
        Optional insertNewLine As Boolean = False,
        Optional appendBoxFont As Drawing.Font = Nothing,
        Optional suspendLayout As Boolean = True,
        Optional updateViewNow As Boolean = False) ' EAHMK 20240122
        If suspendLayout Then ' EAHMK 20240122
            Call appendBox.SuspendLayout()
        End If
        If IsNothing(appendBoxFont) Then
            appendBoxFont = appendBox.Font
        End If
        If insertNewLine Then
            Call appendBox.AppendText(text:=Environment.NewLine)
        End If
        appendBox.SelectionStart = appendBox.TextLength
        appendBox.SelectionLength = 0
        appendBox.SelectionFont = appendBoxFont
        If Not inForeColor.Equals(obj:=Drawing.Color.Empty) Then ' EAHMK 20240122
            appendBox.SelectionColor = inForeColor
        End If
        If Not inBackColor.Equals(obj:=Drawing.Color.Empty) Then ' EAHMK 20240122
            appendBox.SelectionBackColor = inBackColor
        End If
        appendBox.SelectedText = inText
        If suspendLayout Then ' EAHMK 20240122
            Call appendBox.ResumeLayout()
        End If
        If updateViewNow Then
            Call appendBox.Update()
        End If
    End Sub

    ''' <summary>
    ''' Appends colored text to a rich text box. This is the version of 2019.
    ''' The XML comments have been updated on January 22 2024.
    ''' This subroutine will most probably function from VS2013 through VS2022.
    ''' </summary>
    ''' <param name="appendBox">
    ''' The rich text box to append to.
    ''' </param>
    ''' <param name="inText">
    ''' The text to append.
    ''' </param>
    ''' <param name="inColor">
    ''' The color to display the appended text in.
    ''' </param>
    ''' <param name="insertNewLine">
    ''' True means a new line is to be inserted before appending the new text.
    ''' </param>
    ''' <param name="updateViewNow">
    ''' True means the appended text is to be seen as soon as possible.
    ''' </param>
    ''' <remarks>
    ''' Language: VB.NET VS2013, February 23 2019, EAHMK.
    ''' The original C# solution stems from Multiple Colored Texts in RichTextBox
    ''' using C# by S.Vinothkumar, 27 Jun 2009.
    ''' </remarks>
    Public Sub appendColoredTextToRichTextBox(
        appendBox As Windows.Forms.RichTextBox,
        inText As String,
        inColor As Drawing.Color,
        Optional insertNewLine As Boolean = False,
        Optional updateViewNow As Boolean = False)
        Call appendBox.SuspendLayout()
        Dim appendBoxFont As Drawing.Font = appendBox.Font
        If insertNewLine Then
            Call appendBox.AppendText(Environment.NewLine)
        End If
        appendBox.SelectionStart = appendBox.TextLength
        appendBox.SelectionLength = 0
        appendBox.SelectionFont = appendBoxFont
        appendBox.SelectionColor = inColor
        appendBox.SelectedText = inText
        Call appendBox.ResumeLayout()
        If updateViewNow Then
            Call appendBox.Update()
        End If
    End Sub

#End Region ' Colored Texts to a RichTextBox 

Examples

I call appendColoredTextToRichTextBox for error messages like this:

VB.NET
Private Sub showErrorMessage(ex As Exception,
    ByRef showBox As RichTextBox,
    Optional showImmediately As Boolean = False,
    Optional colorToShow As Drawing.Color = Nothing) ' EAHMK 20240122
    If colorToShow.Equals(obj:=Drawing.Color.Empty) Then
        colorToShow = Drawing.Color.Red
    End If
    Call appendColoredTextToRichTextBox(appendBox:=showBox,
            inText:=ex.Message, inColor:=colorToShow,
            insertNewLine:=True, updateViewNow:=showImmediately)
End Sub

I call appendColoredTextToRichTextBox for comment texts like this:

VB.NET
Private Sub showCommentMessage(textToShow As String,
    ByRef showBox As RichTextBox,
    Optional showImmediately As Boolean = False,
    Optional colorToShow As Drawing.Color = Nothing) ' EAHMK 20240122
    If colorToShow.Equals(obj:=Drawing.Color.Empty) Then
        colorToShow = Drawing.Color.Black
    End If
    Call appendColoredTextToRichTextBox(appendBox:=showBox,
            inText:=textToShow, inColor:=colorToShow,
            insertNewLine:=True, updateViewNow:=showImmediately)
End Sub

With the following code, you can test the combined use of the 2024 and the 2019 version.
Replace Me.vermijdRichTextBox with a pointer to a rich textbox of yourself.

VB.NET
Dim exampleRichTextBox As RichTextBox = Me.vermijdRichTextBox ' EAHMK 20240122
Call appendColoredTextToRichTextBox(appendBox:=exampleRichTextBox,
        inText:="  This is darkblue text with the default backcolor  ",
        inColor:=Drawing.Color.DarkBlue)
Call appendColoredTextToRichTextBox(appendBox:=exampleRichTextBox,
        inText:="  This is red text on a new line  ", inColor:=Drawing.Color.Red,
        insertNewLine:=True)
Call appendColoredTextToRichTextBox(appendBox:=exampleRichTextBox,
        inText:="  This is cyan text  ", inColor:=Drawing.Color.Cyan)
Call appendColoredTextToRichTextBox(exampleRichTextBox, "  This is a new line  ",
        inColor:=Drawing.Color.Black, insertNewLine:=True)
exampleRichTextBox.SelectionFont = New Font(family:=
        New FontFamily("Courier New"), emSize:=13, style:=FontStyle.Underline,
        unit:=exampleRichTextBox.Font.Unit)
Call appendColoredTextToRichTextBox(appendBox:=exampleRichTextBox,
        inText:="  This is red underlined text with a monospaced typeface on " &
        "yellow  ", inForeColor:=Drawing.Color.Red, inBackColor:=
        Drawing.Color.Yellow, appendBoxFont:=exampleRichTextBox.SelectionFont)
Call appendColoredTextToRichTextBox(appendBox:=exampleRichTextBox, inText:=
        "  This is darkblue text with the former backcolor  ",
        inColor:=Drawing.Color.DarkBlue)
Call appendColoredTextToRichTextBox(appendBox:=exampleRichTextBox, inText:=
        "  This is cyan on green text  ", inForeColor:=Drawing.Color.Cyan,
        inBackColor:=Drawing.Color.Green)
Call appendColoredTextToRichTextBox(appendBox:=exampleRichTextBox, inText:=
        "  This is a new line with default colors  ", insertNewLine:=True)

Points of Interest

I do not know if appendColoredTextToRichTextBox functions on Windows Presentation Foundation too, since I never use WPF. If someone tried this and gets positive result, please react.

Summary of Changes

Today, January the 22nd of 2024, I updated my article. The following changes have been made:

  • The texts in the blocks Introduction and Background and "Using the Code" and History have been updated.
  • Region "Colored Texts to a RichTextBox" has been added.
  • XML remark part "1, 2, 3 and 4 stem from ..." has been altered to "The original C# solution stems from Multiple Colored Texts in RichTextBox using C# by S.Vinothkumar, 27 Jun 2009."
  • The XML text of parameter updateViewNow has been updated.
  • All parameters now are qualified by parameter names.
  • Example block "Examples" has been added.
  • The 2 examples moved from block "Using the Code" to that block.
  • A new example with rich textbox exampleRichTextBox has been added.
  • Replace Me.vermijdRichTextBox with a pointer to a rich textbox of yourself.
  • This changes list has been added to block History.
  • The name of block History has been changed to "Summary of changes".

A new version of appendColoredTextToRichTextBox has been added.
The below text is about changes from the 2019 to the 2024 version:

  • Parameter inColor has been replaced by optional parameter inForeColor.
  • Optional parameter inBackColor has been added.
  • Optional parameter suspendLayout has been added.
  • Comments 1, 4, 2, 3 and 4 have been removed.
  • Dutch subroutine name foutBericht has been changed to showErrorMessage.
  • Dutch parameters toonMeteen have been changed to showImmediately.
  • The superfluous parameter keywords ByVal have been removed.
  • Dutch parameters kleur have been changed to colorToShow.
  • Rich text box name Me.RichTextBox1 has been changed to a new parameter, named showBox.
  • Dutch subroutine name commentaarTekst has been changed to showCommentMessage.
  • Dutch parameter tekst has been changed to textToShow.

History

  • 25th February, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)