Reputation: 12218
I have RichTextBox
in which I format text, I have there multiple text selections and formats.
Because of that, after the formatting is done, the scrollbars positions of RichTextBox
isn't the same.
How am I able to save and restore scrollbar position same (easy) way as I can save cursor position?
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;
}
Upvotes: 0
Views: 813
Reputation: 12218
I have seen many posts here that were solving this by handling scroll messages.
I have managed this simplier way, so if anyone have the same problem, you can use this way. It is not perfect (if there is a half of line displayed at the top, it will be scrolled), but is enough I think :).
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;
}
Upvotes: 1