如何使用C#在WinForms TextBox中滚动到指定行?
谢谢。
以下是如何滚动到所选内容的方法:
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();
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();
}
我找到了最好的解决方案:
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);
}
它的好处是,选择和插入符位置不会改变。
寻找正确插入符位置的循环答案存在一些问题。首先,对于大型文本框,它速度较慢。其次,制表符似乎会使其混淆。更直接的方法是使用您想要的行上的文本。
String textIWantShown = "Something on this line.";
int position = textBox.Text.IndexOf(textIWantShown);
textBox.SelectionStart = position;
textBox.ScrollToCaret();
这个文本必须是独一无二的,但你可以从textBox.Lines数组中获取它。在我的情况下,我已经将行号添加到我显示的文本中,所以这使得操作更加简单。