Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I scroll to a specified line in a WinForms TextBox using C#?

How can I scroll to a specified line in a WinForms TextBox using C#?

Thanks

like image 648
alinpopescu Avatar asked Apr 11 '09 07:04

alinpopescu


2 Answers

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();
like image 98
dommer Avatar answered Oct 07 '22 13:10

dommer


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.

like image 43
user1027167 Avatar answered Oct 07 '22 11:10

user1027167