RichTextBox控件有一个Lines属性,该属性是数组类型,它的每一项对应着RichTextBox控件中的一行。每一项都有对应行的Length属性。那么我们就可以像这样来设置光标:
private void GoToLineAndColumn(RichTextBox rtb, int line, int column)
{
rtb.Focus();
if (line < 0 || column < 0) { rtb.SelectionStart = 0; } else { if (line > rtb.Lines.Length - 1)
{
rtb.SelectionStart = rtb.GetFirstCharIndexFromLine(rtb.Lines.Length - 1)
+ rtb.Lines[rtb.Lines.Length - 1].Length;
}
else
{
int firstCharIndexOfline = rtb.GetFirstCharIndexFromLine(line);
int textlengthOfline;
textlengthOfline = rtb.Lines[line].Length;
if (column > textlengthOfline)
column = textlengthOfline;
rtb.SelectionStart = firstCharIndexOfline + column;
}
}
}