我想制作一个框,我可以在其中显示某些文字左侧导向和某些文字在C#中正确定位。 例如,
代码
If (msg from admin)
richTextBox.Append(rightAligned(msg))
else
richTextBox.Append(leftAligned(msg))
我尝试了SelectionAlignment
的{{1}}功能,但它对框中的所有文字都应用了特定的格式。我怎样才能达到预期的效果?任何帮助将不胜感激。
答案 0 :(得分:3)
您可以将Environment.Newline
和RichTextBox.SelectionAlignment
用于richTextBox。
例如:
if (msg from admin) {
richTextBox.AppendText(Environment.NewLine + msg);
richTextBox.SelectionAlignment = HorizontalAlignment.Right;
} else {
richTextBox.AppendText(Environment.NewLine + msg);
richTextBox.SelectionAlignment = HorizontalAlignment.Left;
}
答案 1 :(得分:1)
这也可以这样做:)
If (...)
{
textBox1.TextAlign = HorizontalAlignment.Left;
textBox1.Text = " Blah Blah ";
}
else
{
textBox1.TextAlign = HorizontalAlignment.Right;
textBox1.Text = " Blah Blah Right";
}
答案 2 :(得分:1)
要设置追加文本的对齐方式,您只需选择附加文本,然后使用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.
}
答案 3 :(得分:0)
您想使用RichTextBox.SelectionAlignment。从another SO answer无耻地偷走。
看来您必须附加文本,选择它然后更改SelectionAlignment。