C# Windows 窗体 RichTextBox 光标位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2241862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Windows Forms RichTextBox cursor position
提问by QAH
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.
我有一个带有 RichTextBox 控件的 C# Windows 窗体程序。每当框中的文本发生更改(而不是键入更改)时,光标都会返回到开头。
In other words, when the text in the RichTextBox is changed by using the Text property, it makes the cursor jump back.
换句话说,当 RichTextBox 中的文本被 Text 属性改变时,它会使光标跳回。
How can I keep the cursor in the same position or move it along with the edited text?
如何将光标保持在同一位置或随编辑的文本一起移动?
Thanks
谢谢
采纳答案by Mark Byers
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.
如果您不想删除突出显示,您可能还想对 SelectionLength 执行相同的操作。请注意,如果插入的文本在选择范围内,这可能会导致奇怪的行为。然后您需要扩展选择以包括插入文本的长度。
回答by GoRoS
Be careful, if someone refreshes or changes totally the RichTextBox content, the focus method must be invoqued previously in order to move the caret:
请注意,如果有人刷新或完全更改 RichTextBox 内容,则必须先调用 focus 方法才能移动插入符号:
richTextBox1.Focus();
int i = richTextBox1.SelectionStart;
richTextBox1.Text = strPreviousBuffer;
richTextBox1.SelectionStart = i;
回答by justJulian
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
这是一个较小的,具有相同的效果。this.richTextBox1.Select(this.richTextBox1.Text.Length, 0);
在文本末尾标记 0 个字符并将光标设置为结束