我有RichTextBox
,我在其中格式化文本,我有多个文本选择和格式。
完成后,RichTextBox
的滚动条位置是不一样的。
我如何能够像保存光标位置一样(简单)保存和恢复滚动条位置?
protected override void OnTextChanged(EventArgs e)
{
// Save cursor position
int cursor_position = this.SelectionStart;
// Format text
Highlight();
// Restore position
this.SelectionLength = 0;
this.SelectionStart = cursor_position;
}
我在这里看到很多帖子通过处理滚动消息来解决这个问题。
我已经管理了这种更简单的方法,所以如果有人有同样的问题,你可以使用这种方式。它并不完美(如果顶部显示半行,它将被滚动),但我认为:)就足够了。
protected override void OnTextChanged(EventArgs e)
{
// Get first and last displayed character
int start = this.GetCharIndexFromPosition(new Point(0, 0));
int end = this.GetCharIndexFromPosition(new Point(this.ClientSize.Width, this.ClientSize.Height));
// Save cursor position
int cursor_position = this.SelectionStart;
int cursor_lenght = this.SelectionLength;
// Your formatting
Highlight();
// Scroll to the last character and then to the first + line width
this.SelectionLength = 0;
this.SelectionStart = end;
this.ScrollToCaret();
this.SelectionStart = start + this.Lines[this.GetLineFromCharIndex(start)].Length+1;
this.ScrollToCaret();
// Finally, set cursor to original position
this.SelectionStart = cursor_position;
}