15

I have a C# Windows Forms program that has a RichTextBox control. Whenever the text inside the box is changed (other than typing that change), the cursor goes back to the beginning.

In other words, when the text in the RichTextBox is changed by using the Text property, it makes the cursor jump back.

How can I keep the cursor in the same position or move it along with the edited text?

Thanks

General Grievance
  • 4,555
  • 31
  • 31
  • 45
QAH
  • 4,200
  • 13
  • 44
  • 52

3 Answers3

21

You can store the cursor position before making the change, and then restore it afterwards:

int i = richTextBox1.SelectionStart;
richTextBox1.Text += "foo";
richTextBox1.SelectionStart = i;

You might also want to do the same with SelectionLength if you don't want to remove the highlight. Note that this might cause strange behaviour if the inserted text is inside the selection. Then you will need to extend the selection to include the length of the inserted text.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 2
    The cursor position and SelectionStart aren't always the same. In the case where there is text selected, the caret can be either at the beginning of the selected text or at the end, depending on which direction the text was selected. Sadly, Winforms RichTextBox doesn't seem to have a separate property for this. – cat_in_hat Aug 08 '18 at 16:58
5

Be careful, if someone refreshes or changes totally the RichTextBox content, the focus method must be invoqued previously in order to move the caret:

richTextBox1.Focus();
int i = richTextBox1.SelectionStart;
richTextBox1.Text = strPreviousBuffer;
richTextBox1.SelectionStart = i;
GoRoS
  • 5,183
  • 2
  • 43
  • 66
3

here's a smaller one, that has the same effect. this.richTextBox1.Select(this.richTextBox1.Text.Length, 0); That marks 0 chars at the end of the text and sets the cursor to end

justJulian
  • 31
  • 1