سؤال

I used following code to color lines.

For line As Integer = 1 To RichTextBox1.Lines.Count() - 1
            If RichTextBox1.Lines(line).StartsWith("You:") Then
                RichTextBox1.Select(RichTextBox1.GetFirstCharIndexFromLine(line), RichTextBox1.Lines(line).Length)
                RichTextBox1.SelectionColor = Color.Black
            Else
                RichTextBox1.Select(RichTextBox1.GetFirstCharIndexFromLine(line), RichTextBox1.Lines(line).Length)
                RichTextBox1.SelectionColor = System.Drawing.ColorTranslator.FromHtml(color1)
            End If
        Next

It works fine when each line is actually one line long. However if one message is longer it breaks whole coloring below the line: wrong coloring

On the picture the last line should be colored black, but second was colored instead.

How can I fix this?

هل كانت مفيدة؟

المحلول

When WordWrap is True, the Lines() array will return every line as you see it in the control, so a "wrapped" line is getting treated as a new line.

Try splitting on the line feed character and calculate the positions yourself:

Dim lines() As String = RichTextBox1.Text.Split(vbLf)
Dim startIndex As Integer = 0
For i As Integer = 0 To lines.Length - 1
  RichTextBox1.Select(startIndex, lines(i).Length)
  If lines(i).StartsWith("You:") Then
    RichTextBox1.SelectionColor = Color.Red
  Else
    RichTextBox1.SelectionColor = Color.Green
  End If
  startIndex += lines(i).Length + vbLf.Length
Next

نصائح أخرى

If you set RichTextBox1.WordWrap to False it works as expected.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top