2014-11-21 112 views
3

我想製作一個框,我可以在C#中顯示某些文本左側和某些文本右側。 例如,左右對齊richtextbox c#

代碼

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

我試過的richTextBoxSelectionAlignment功能,但它適用於特定的格式在框中的所有文本。我怎樣才能達到預期的效果?任何幫助將不勝感激。

+0

這將是更好的,如果你使用面板而不是RichTExtBox ... – yash 2014-11-21 05:28:09

回答

3

對於您的richTextBox,您可以使用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; 
} 
+1

非常感謝,這完美的作品,我的例子 – Rukshod 2014-11-22 07:08:57

1

可以這樣做,以及:)

If (...) 
    { 
     textBox1.TextAlign = HorizontalAlignment.Left; 
     textBox1.Text = " Blah Blah "; 
    } 
else 
    { 
     textBox1.TextAlign = HorizontalAlignment.Right; 
     textBox1.Text = " Blah Blah Right"; 
    } 
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. 
    }