Format text in a RichTextBox in C#

[RichTextBox]

To format text in a RichTextBox, use the control’s Select method to select the text. Then use the “Selection” properties (SelectionAlignment, SelectionBackColor, SelectionFont, etc.) to set the properties for the selected text.

This example uses the following code to format three pieces of text in the first RichTextBox.

// Format RichTextBox1.
richTextBox1.Select(4, 5);
richTextBox1.SelectionColor = Color.Red;
richTextBox1.Select(16, 3);
richTextBox1.SelectionFont =
    new Font(richTextBox1.Font, FontStyle.Italic);
richTextBox1.Select(35, 4);
richTextBox1.SelectionBackColor = Color.Yellow;
richTextBox1.SelectionColor = Color.Brown;
richTextBox1.Select(0, 0);

To make formatting a little easier, the following SelectRichText method selects a target string within a RichTextBox.

// Select the indicated text.
private void SelectRichText(RichTextBox rch, string target)
{
    int pos = rch.Text.IndexOf(target);
    if (pos < 0)
    {
        // Not found. Select nothing.
        rch.Select(0, 0);
    }
    else
    {
        // Found the text. Select it.
        rch.Select(pos, target.Length);
    }
}

The program uses this method to format text in its second RichTextBox as shown in the following code.

SelectRichText(richTextBox2, "quick");
richTextBox2.SelectionColor = Color.Red;


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *