Home > Software engineering >  How do I set text background color without changing cursor location?
How do I set text background color without changing cursor location?

Time:11-01

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related