How can I scroll to a specified line in a WinForms TextBox using C#?
Thanks
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With