右对齐和左对齐格式文本框 c#

本文关键字:文本 格式 左对齐 右对齐 | 更新日期: 2023-09-27 18:31:24

我想创建一个框,在其中我可以在 C# 中显示某些向左的文本和向右显示某些文本。例如

法典

If (msg from admin)
   richTextBox.Append(rightAligned(msg))
else
   richTextBox.Append(leftAligned(msg))

我尝试了SelectionAlignment richTextBox的功能,但它对框中的所有文本应用了特定的格式。我怎样才能达到预期的结果?任何帮助将不胜感激。

右对齐和左对齐格式文本框 c#

你可以

对你的富文本框使用Environment.NewlineRichTextBox.SelectionAlignment

例如:

if (msg from admin) {
    richTextBox.AppendText(Environment.NewLine + msg);
    richTextBox.SelectionAlignment = HorizontalAlignment.Right;
} else {
    richTextBox.AppendText(Environment.NewLine + msg);
    richTextBox.SelectionAlignment = HorizontalAlignment.Left;
}

要仅设置追加文本的对齐方式,只需选择追加文本,然后使用 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();
    }

经过一番测试,似乎只要text字符串不包含换行符,仅设置SelectionAlignment就可以工作,但如果有嵌入的换行符,则只有最后一个附加的行正确对齐。

    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.
    }

也可以:)

 If (...)
    {
       textBox1.TextAlign = HorizontalAlignment.Left;
       textBox1.Text = " Blah Blah ";
    }
else
   {
       textBox1.TextAlign = HorizontalAlignment.Right;
       textBox1.Text = " Blah Blah Right";
   }

你想使用 RichTextBox.SelectionAlignment。无耻地从另一个SO答案中偷来。

看起来您必须附加文本,选择它,然后更改选择对齐方式。