views:

630

answers:

1

Hello everyone! 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

+1  A: 

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