简体   繁体   中英

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

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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM