如何使用 C# 滚动到 RichTextBox 控件的指定行号?

发布于 2024-10-05 13:02:00 字数 53 浏览 0 评论 0原文

如何使用 C# 滚动到 RichTextBox 控件的指定行号?这是WinForms 版本。

How can I scroll to a specified line number of a RichTextBox control using C#? It's the WinForms version.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

樱花落人离去 2024-10-12 13:02:00

你可以尝试这样的事情。

    void ScrollToLine(int lineNumber)
    {
        if (lineNumber > richTextBox1.Lines.Count()) return;

        richTextBox1.SelectionStart = richTextBox1.Find(richTextBox1.Lines[lineNumber]);
        richTextBox1.ScrollToCaret();
    }

如果您的 RichTextBox 中有大量重复内容,这将无法完美工作。我确实希望它对您有用。

You can try something like this.

    void ScrollToLine(int lineNumber)
    {
        if (lineNumber > richTextBox1.Lines.Count()) return;

        richTextBox1.SelectionStart = richTextBox1.Find(richTextBox1.Lines[lineNumber]);
        richTextBox1.ScrollToCaret();
    }

This will not work perfectly if you have lots of repetition within your RichTextBox. I do hope that it might be of some use to you.

眼睛会笑 2024-10-12 13:02:00

使用此代码,光标跳转到所需行中的第一列。

在任何情况下它都能完美运行,即使所需的线路出现多次。

void GotoLine(int wantedLine_zero_based) // int wantedLine_zero_based = wanted line number; 1st line = 0
{
    int index = this.RichTextbox.GetFirstCharIndexFromLine(wantedLine_zero_based);
    this.RichTextbox.Select(index, 0);
    this.RichTextbox.ScrollToCaret();
}

With this code the cursor jumps to the first column in the wanted line.

It works perfectly in any case, even when the wanted line occurs several times.

void GotoLine(int wantedLine_zero_based) // int wantedLine_zero_based = wanted line number; 1st line = 0
{
    int index = this.RichTextbox.GetFirstCharIndexFromLine(wantedLine_zero_based);
    this.RichTextbox.Select(index, 0);
    this.RichTextbox.ScrollToCaret();
}
还给你自由 2024-10-12 13:02:00

我不确定它是否有一个方法,但是如何计算 Text 中的换行符,然后设置插入符号(通过 SelectionStartSelectionLength)和ScrollToCaret()

I'm not sure, if it has a method for this, but how about counting the linebreaks in the Text and then set the caret (via SelectionStart and SelectionLength) and ScrollToCaret()?

筱果果 2024-10-12 13:02:00

在这种情况下拆分文本会有帮助吗?
例如:

string[]lines = myRichTextBox.Text.Split('\n');
intlinesCount =lines.Length;

这会告诉您行数。

Would it help in this situation to split up the text?
For example:

string[] lines = myRichTextBox.Text.Split('\n');
int linesCount = lines.Length;

This will tell you the number of lines.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文