2013-12-23 46 views
0

我有RichTextBox其中我格式的文本,我有那里多个文本选择和格式。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; 
} 

回答

1

我看到很多帖子在这里通过处理滚动消息来解决这个问题。

我已经管理了这种简单的方式,所以如果任何人有同样的问题,你可以使用这种方式。这并不完美(如果在顶部显示一半的行,它会滚动),但我认为是足够的:)。

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; 
}