How to 'align' text in RichTextBox C#?

user488792 picture user488792 · Jun 5, 2011 · Viewed 42.3k times · Source

How do I align the text in a RichTextBox?

RTB

Basically, the RTB contains:

"--testing"

"--TESTING"

"TESTING--"

"testing--"

Which all have the same number of characters, but have different alignments. How can I align them properly? Im fairly new to C# and confused since it aligned properly in Java's TextArea.

Thank you!

Answer

Jason Moore picture Jason Moore · Jun 5, 2011

You want to use the RichTextBox.SelectionAlignment property.

For instance if you want the whole textbox centered, then you would do:

richTextBox1.SelectAll();
richTextBox1.SelectionAlignment = HorizontalAlignment.Center;

If you want only part of the textbox with a certain alignment, then use the RichTextBox.Select() routine to select the text, then set the SelectionAlignment property.