There are a couple different methods that can be used here. The first changes focus, so may not be possible if you have controls that fire validation. The second uses interop, which requires full trust.
Method 1:
Eric Terrell suggested this solution in an email to winformsfaq@syncfusion.com.
The richtextbox control contains a Lines array property, one entry for every line. Each line entry has a Length property. With this information, you can position the selection cursor using code such as:
private void GoToLineAndColumn(RichTextBox RTB, int Line, int Column)
{
int offset = 0;
for (int i = 0; i < Line - 1 && i < RTB.Lines.Length; i++)
{
offset += RTB.Lines[i].Length + 1;
}
RTB.Focus();
RTB.Select(offset + Column, 0);
}
(Note: you may want to store this.ActiveControl to be retrieved after calling Select()).
Method 2:
const int SB_VERT = 1;
const int EM_SETSCROLLPOS = 0x0400 + 222;
[DllImport('user32', CharSet=CharSet.Auto)]
public static extern bool GetScrollRange(IntPtr hWnd, int nBar, out int lpMinPos, out int lpMaxPos);
[DllImport('user32', CharSet=CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, POINT lParam);
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
public POINT()
{
}
public POINT(int x, int y)
{
this.x = x;
this.y = y;
}
}
// Example -- scroll the RTB so the bottom of the text is always visible.
int min, max;
GetScrollRange(richTextBox1.Handle, SB_VERT, out min, out max);
SendMessage(richTextBox1.Handle, EM_SETSCROLLPOS, 0, new POINT(0, max - richTextBox1.Height));
Share with