Daniel Morris Daniel Morris - 6 months ago 12
Vb.net Question

How do I add a new line without deleting text in a RichTextBox and change it's colour in VB.Net?

I can't seem to find the answer anyway. But my Question is;

In visual basic I want to make something called a problem panel and to test it I am making a debug. It uses a progress bar and timer. Here is some of the code so far.

ProgressBar1.Increment(1)
If ProgressBar1.Value = 1 Then
RichTextBox1.Text = "A developer debug has been executed, please wait"
End If

If ProgressBar1.Value = 3 Then
RichTextBox1.SelectionStart = RichTextBox1.Text.Length + 1
RichTextBox1.Text &= "."
End If

If ProgressBar1.Value = 5 Then
RichTextBox1.SelectionStart = RichTextBox1.Text.Length + 1
RichTextBox1.Text &= "."
End If

If ProgressBar1.Value = 7 Then
RichTextBox1.SelectionStart = RichTextBox1.Text.Length + 1
RichTextBox1.Text &= "."
End If

If ProgressBar1.Value = 10 Then
RichTextBox1.Text &= Environment.NewLine & "Testing Warnings"
RichTextBox1.SelectionColor = Color.Yellow
End If

If ProgressBar1.Value = 15 Then
RichTextBox1.SelectionColor = Color.Yellow
RichTextBox1.Text += Environment.NewLine + "Warning"
End If


Basically all it does is create a line, adds a new one and continues typing text. But I can't get it to add a new line. Print 'Warnings' and change that text to Yellow. But using all the code on the internet it stays white?

If anyone can help, it would be much appreciated.

If it's not clear let me summarize:

*Print's text and keeps everything white.

*Prints a new line with everything staying in the RichTextBox.

*The Text will say, Critical, Warning, Information, etc.

*And It needs to change the colour of the text but not change all of the other printed text colour.

Thanks in advance

Answer

Here is a subroutine that will help you:

Private Sub AppendTextWithColor(rich_text_box As RichTextBox, color As Color, text As String)
    Dim length_before = rich_text_box.TextLength

    rich_text_box.AppendText(text)

    Dim length_after = rich_text_box.TextLength

    rich_text_box.SelectionStart = length_before
    rich_text_box.SelectionLength = length_after - length_before
    rich_text_box.SelectionColor = color
End Sub

It allows you to append some text to the RichTextBox with a specific color.

You can use it like this:

AppendTextWithColor(RichTextBox1, Color.Yellow, Environment.NewLine + "Warning")

It works by recording the length of the RichTextBox's text before and after appending the new text. It then sets the SelectionStart and SelectionLength based on the recorded lengths to select the appended text. It then changes the color of the selected text using the SelectionColor property.

Comments