获取/设置富文本框的第一行可见行

本文关键字:一行 设置 文本 获取 | 更新日期: 2023-09-27 18:27:00

我有一个包含数千行文本的RichTextBox。我可以通过使用ScrollToCaret()轻松地SET第一条可见线......

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

但我也希望能够GET第一行可见的行。有什么建议吗?

获取/设置富文本框的第一行可见行

以下是您需要的:

//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];

对于您的评论说您想要一些对应于RichTextBox Width的行,您可以执行以下操作:

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