Windows 窗体 RichTextBox 光标位置
我有一个带有 RichTextBox 控件的 C# Windows 窗体程序。每当框中的文本发生更改(除了键入该更改之外)时,光标都会返回到开头。
换句话说,当使用 Text 属性更改 RichTextBox 中的文本时,它会使光标跳回。
如何将光标保持在同一位置或随编辑的文本一起移动?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在进行更改之前存储光标位置,然后在之后恢复它:
如果您不想删除突出显示,您可能还需要对 SelectionLength 执行相同的操作。请注意,如果插入的文本位于所选内容内,这可能会导致奇怪的行为。然后,您需要扩展选择以包含插入文本的长度。
You can store the cursor position before making the change, and then restore it afterwards:
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.
请注意,如果有人刷新或完全更改了 RichTextBox 内容,则必须事先调用 focus 方法才能移动插入符号:
Be careful, if someone refreshes or changes totally the RichTextBox content, the focus method must be invoqued previously in order to move the caret:
这是一个较小的,具有相同的效果。
this.richTextBox1.Select(this.richTextBox1.Text.Length, 0);
在文本末尾标记 0 个字符并将光标设置为结束
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