1

I want to set the background color of a certain text range in a RichTextBox.

However, the only way to do that is by selecting it like that:

    RichTextBox1.Select(10, 3) 'select text starting from position 10, use a length of 3
    RichTextBox1.SelectionBackColor = Color.White

Using .Select puts the cursor at this location.

How do I achieve the same without changing the cursor location?

Solutions have been posted which just reset the cursor, but this does not help. I need a method would not set the cursor to a different location.

tmighty
  • 10,734
  • 21
  • 104
  • 218

2 Answers2

1

To preserve the previous caret position and selection too:


... Call to suspend drawing here 

var start = richTextBox1.SelectionStart;
var len = richTextBox1.SelectionLength;

richTextBox1.Select(10, 3); 
richTextBox1.SelectionBackColor = Color.White;

richTextBox1.SelectionStart = start;
richTextBox1.SelectionLength = len;

... Call to resume drawing here 

To prevent flicking check the solution provided in this post: https://stackoverflow.com/a/487757/6630084


TextBoxBase.SelectionStart Property

TextBoxBase.SelectionLength Property

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
  • Unfortunately this still makes the cursor jump around, you can see it flicker. – tmighty Oct 31 '22 at 19:10
  • @tmighty: To prevent flickering try to suspend drawing before making selection and resume drawing after. I have added reference to the related SO post. – Jackdaw Oct 31 '22 at 19:41
0

You can store the cursor position before setting the color, then restore the position as follows:

Public Sub New()
    InitializeComponent()
    richTextBox1.Text += "RichTextBox text line 1" & Environment.NewLine
    richTextBox1.Text += "RichTextBox text line 2" & Environment.NewLine
    richTextBox1.Text += "RichTextBox text line 3" & Environment.NewLine

    Dim i As Integer = richTextBox1.SelectionStart
    Dim j As Integer = richTextBox1.SelectionLength

    richTextBox1.Select(10, 3)
    richTextBox1.SelectionBackColor = Color.White

    richTextBox1.SelectionStart = i
    richTextBox1.SelectionLength = j 'use this to preserve selection length, or
    richTextBox1.SelectionLength = 0 'use this to clear the selection
End Sub
evilmandarine
  • 4,241
  • 4
  • 17
  • 40