テキストが aTextBox
または aにあるRichTextBox
場合は、コントロールを選択してカーソルを置くことができます
// Set the cursor into the text box
bodyTextBox.Focus();
// Place the cursor at the desired position in the text
bodyTextBox.Select(start, 0);
3行目がどこから始まるかを把握する必要があります
const int indent = 30; // Desired indentation
// Place focus in this control
bodyTextBox.Focus();
// The following work only if we have at least 3 lines of text
if (bodyTextBox.Lines.Length >= 3) {
int start = bodyTextBox.Lines[0].Length + // Length of first line
bodyTextBox.Lines[1].Length + // Length of second line
4 + // 2 x 2 characters for two CR-LFs
Math.Min(indent, bodyTextBox.Lines[2].Length);
bodyTextBox.Select(start, 0);
}
文章はこんな感じだと思います
テキストの最初の行。<CR><LF>
テキストの 2 行目。<CR><LF>
<インデントは30スペース>
^ 希望の位置
カーソルを正しい位置に設定するには、テキストの先頭から合計文字数をカウントする必要があります。カーソルを 3 行目に配置したいので、これは、最初の 2 行と、その末尾にある 2 つの CR-LF (改行文字) と、3 行目の先頭にある 30 文字の長さです。3 行目が 30 文字未満の場合、そこにカーソルを配置することはできません。したがって、カーソルをできるだけ右側に配置します。つまり、この行の最後の文字にMath.Min(indent, bodyTextBox.Lines[2].Length);
最後に でカーソルをそこに置きますSelect
。テキストを選択したくないので、選択の長さをゼロと定義します。