如何使用 C# 滚动到 WinForms TextBox 中的指定行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/739656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I scroll to a specified line in a WinForms TextBox using C#?
提问by alinpopescu
How can I scroll to a specified line in a WinForms TextBox using C#?
如何使用 C# 滚动到 WinForms TextBox 中的指定行?
Thanks
谢谢
回答by dommer
Here's how you scroll to the selection:
以下是滚动到选择的方法:
textBox.ScrollToCaret();
To scroll to a specified line, you could loop through the TextBox.Lines property, total their lengths to find the start of the specified line and then set TextBox.SelectionStart to position the caret.
要滚动到指定的行,您可以循环遍历 TextBox.Lines 属性,合计它们的长度以找到指定行的开头,然后设置 TextBox.SelectionStart 以定位插入符号。
Something along the lines of this (untested code):
类似的东西(未经测试的代码):
int position = 0;
for (int i = 0; i < lineToGoto; i++)
{
position += textBox.Lines[i].Length;
}
textBox.SelectionStart = position;
textBox.ScrollToCaret();
回答by dommer
The looping answer to find the proper caret position has a couple of problems. First, for large text boxes, it's slow. Second, tab characters seem to confuse it. A more direct route is to use the text on the line that you want.
找到正确插入符号位置的循环答案有几个问题。首先,对于大文本框,它很慢。其次,制表符似乎混淆了它。更直接的方法是使用您想要的行上的文本。
String textIWantShown = "Something on this line.";
int position = textBox.Text.IndexOf(textIWantShown);
textBox.SelectionStart = position;
textBox.ScrollToCaret();
This text must be unique, of course, but you can obtain it from the textBox.Lines array. In my case, I had prepended line numbers to the text I was displaying, so this made life easier.
当然,此文本必须是唯一的,但您可以从 textBox.Lines 数组中获取它。就我而言,我在显示的文本前添加了行号,因此这让生活更轻松。
回答by Timothy Klenke
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();
}
回答by user1027167
This is the best solution I found:
这是我找到的最佳解决方案:
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);
}
It has the benefit, that the selection and caret position is not changed.
它的好处是,选择和插入符号的位置不会改变。