Windows Forms RichTextBox cursor position

前端 未结 3 1414
忘了有多久
忘了有多久 2021-01-17 11:27

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 be

3条回答
  •  甜味超标
    2021-01-17 12: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.

提交回复
热议问题