Advanced 15 min read Control #22

RichTextBox Control

RichTextBox is like TextBox on steroids. It supports formatted text with different fonts, colors, sizes, and styles. It's like a mini word processor.

What is a RichTextBox?

RichTextBox supports rich text formatting. You can change font, color, size, bold, italic, underline, and even load/save RTF files. It's perfect for note-taking apps, text editors, and document editing.

Code Example

// Format selected text
private void btnBold_Click(object sender, EventArgs e)
{
    if (richTextBox1.SelectionLength > 0)
    {
        var style = richTextBox1.SelectionFont.Style;
        if ((style & FontStyle.Bold) == FontStyle.Bold)
            style &= ~FontStyle.Bold;
        else
            style |= FontStyle.Bold;
        
        richTextBox1.SelectionFont = new Font(
            richTextBox1.SelectionFont, style);
    }
}

// Change selection color
private void btnColor_Click(object sender, EventArgs e)
{
    using (var colorDialog = new ColorDialog())
    {
        if (colorDialog.ShowDialog() == DialogResult.OK)
        {
            richTextBox1.SelectionColor = colorDialog.Color;
        }
    }
}

// Load/Save RTF files
private void LoadRtfFile(string path)
{
    richTextBox1.LoadFile(path);
}

private void SaveRtfFile(string path)
{
    richTextBox1.SaveFile(path);
}

Exercise

Task: Create a simple text editor with RichTextBox.

  1. Add a RichTextBox with Dock = Fill.
  2. Add a MenuStrip with: File (New, Open, Save, Save As).
  3. Add a ToolStrip with: Bold, Italic, Underline, Color.
  4. Add Font and Size ComboBoxes.
  5. Add alignment buttons (Left, Center, Right).
  6. Add a status bar showing character count.
Key Takeaway

RichTextBox is a powerful text editing control. Use it for formatted text, RTF documents, and creating mini word processors.