Michael Mankus
Michael Mankus

Reputation: 4778

Get/Set First Visible Line of RichTextBox

I have a RichTextBox with thousands of lines of text in it. I can easily SET the first visible line by using ScrollToCaret() by doing...

this.SelectionStart = this.Find(this.Lines[lineIndex], RichTextBoxFinds.NoHighlight);
this.ScrollToCaret();

But I would like to be able to GET the first visible line too. Any suggestions?

Upvotes: 11

Views: 7842

Answers (1)

King King
King King

Reputation: 63317

Here may be what you need:

//get the first visible char index
int firstVisibleChar = richTextBox1.GetCharIndexFromPosition(new Point(0,0));
//get the line index from the char index
int lineIndex = richTextBox1.GetLineFromCharIndex(firstVisibleChar);
//just get the string of the line
string firstVisibleLine = richTextBox1.Lines[lineIndex];

For your comment saying that you want some line accordingly to the Width of the RichTextBox, you can do something like this:

int firstVisibleChar = richTextBox1.GetCharIndexFromPosition(new Point(0,0));
int lastChar = richTextBox1.GetCharIndexFromPosition(new Point(richTextBox1.ClientSize.Width - 1, 1));
string firstVisibleLine = richTextBox1.Text.Substring(firstVisibleChar, lastChar - firstVisibleChar);

Upvotes: 18

Related Questions