如何使用 C# 滚动到 WinForms TextBox 中的指定行?

问题描述 投票:0回答:5

如何使用 C# 滚动到 WinForms TextBox 中的指定行?

谢谢

c# winforms textbox line
5个回答
29
投票

以下是滚动到所选内容的方法:

textBox.ScrollToCaret();

要滚动到指定行,您可以循环遍历 TextBox.Lines 属性,合计它们的长度以找到指定行的开头,然后设置 TextBox.SelectionStart 来定位插入符号。

与此类似的内容(未经测试的代码):

int position = 0;

for (int i = 0; i < lineToGoto; i++)
{
    position += textBox.Lines[i].Length;
}

textBox.SelectionStart = position;

textBox.ScrollToCaret();

10
投票
    private void MoveCaretToLine(TextBox txtBox, int lineNumber)
    {
        txtBox.HideSelection = false;
        txtBox.SelectionStart = txtBox.GetFirstCharIndexFromLine(lineNumber - 1);
        txtBox.SelectionLength = txtBox.Lines[lineNumber - 1].Length;
        txtBox.ScrollToCaret();
    }

3
投票

这是我找到的最好的解决方案:

const int EM_GETFIRSTVISIBLELINE = 0x00CE;
const int EM_LINESCROLL = 0x00B6;

[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

void SetLineIndex(TextBox tbx, int lineIndex)
{
  int currentLine = SendMessage(textBox1.Handle, EM_GETFIRSTVISIBLELINE, 0, 0);
  SendMessage(tbx.Handle, EM_LINESCROLL, 0, lineIndex - currentLine);
}

它的好处是选择和插入符位置不会改变。


0
投票

找到正确插入符位置的循环答案有几个问题。首先,对于大型文本框,速度很慢。其次,制表符似乎让人困惑。更直接的途径是使用您想要的行上的文本。

String textIWantShown = "Something on this line.";
int position = textBox.Text.IndexOf(textIWantShown);
textBox.SelectionStart = position;
textBox.ScrollToCaret();

当然,这个文本必须是唯一的,但是你可以从textBox.Lines数组中获取它。就我而言,我在显示的文本前面添加了行号,因此这让生活变得更轻松。


0
投票

我找到了用户1027167的答案:

void SetLineIndex(TextBox tbx, int lineIndex)
{
  int currentLine = SendMessage(textBox1.Handle

有助于解决我的问题(我有一个文本框,它演示了所选文本的样子,我希望插入光标位于 0,同时保持选择)。不过,好像有一个错字:

void SetLineIndex(TextBox pTheTextBox, int lineIndex)
{
  int currentLine = SendMessage(pTheTextBox.Handle

在最简单的测试用例中,使用单个 TextBox,这两个变量通常会解析为同一个 TextBox。

© www.soinside.com 2019 - 2024. All rights reserved.