Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 480
QAH Avatar asked Feb 11 '10 02:02

QAH


People also ask

What is RichTextBox in Windows Form applications?

The Windows Forms RichTextBox control is used for displaying, entering, and manipulating text with formatting. The RichTextBox control does everything the TextBox control does, but it can also display fonts, colors, and links; load text and embedded images from a file; and find specified characters.

How do you move the cursor to the end of the text in a TextBox C#?

To position the cursor at the end of the contents of a TextBox control, call the Select method and specify the selection start position equal to the length of the text content, and a selection length of 0.


2 Answers

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.

like image 59
Mark Byers Avatar answered Sep 21 '22 06:09

Mark Byers


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;
like image 33
GoRoS Avatar answered Sep 21 '22 06:09

GoRoS