QAH
QAH

Reputation: 4280

Windows Forms RichTextBox cursor position

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

Upvotes: 15

Views: 40799

Answers (3)

justJulian
justJulian

Reputation: 31

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

Upvotes: 3

GoRoS
GoRoS

Reputation: 5375

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;

Upvotes: 5

Mark Byers
Mark Byers

Reputation: 838106

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.

Upvotes: 21

Related Questions