Чтобы просто установить выравнивание текста в добавляется, вам нужно выбрать только прилагаемый текст, затем используйте свойство SelectionAlignment
:
public static void AppendLineAndAlignText(this RichTextBox richTextBox, string text, HorizontalAlignment alignment)
{
if (string.IsNullOrEmpty(text))
return;
var index = richTextBox.Lines.Length; // Get the initial number of lines.
richTextBox.AppendText("\n" + text); // Append a newline, and the text (which might also contain newlines).
var start = richTextBox.GetFirstCharIndexFromLine(index); // Get the 1st char index of the appended text
var length = richTextBox.Text.Length;
richTextBox.Select(start, length - index); // Select from there to the end
richTextBox.SelectionAlignment = alignment; // Set the alignment of the selection.
richTextBox.DeselectAll();
}
После тестирования немного кажется, что только установка SelectionAlignment
будет работать до тех пор, пока строка text
не содержит символов новой строки, но если есть встроенные строки новой строки, только последняя добавленная строка выравнивается правильно.
public static void AppendLineAndAlignText(this RichTextBox richTextBox, string text, HorizontalAlignment alignment)
{
// This only works if "text" contains no newline characters.
if (string.IsNullOrEmpty(text))
return;
richTextBox.AppendText("\n" + text); // Append a newline, and the text (which must not also contain newlines).
richTextBox.SelectionAlignment = alignment; // Set the alignment of the selection.
}
Это будет лучше, если вы используете панель Вместо RichTextBox ... – yash