Hi,

I have a problem with showing text in different fonts, fontstyles, colors, alignments and sizes in richTextBox in C#. I read some articles on Internet about this, but I was't satisfied with them. Many thanks in advance.

regards,

Bojan

Dani AI

Generated

Short practical guide (follow-up to ; was right to point at the docs) with working patterns, common pitfalls and small code samples you can drop into a WinForms app.

The WinForms RichTextBox exposes selection-based properties you should use: SelectionFont, SelectionColor and SelectionAlignment (they affect the selection or the insertion point). Use the selection APIs to change only part of the text rather than rewriting Text. (learn.microsoft.com)

Example — change styling for the current selection, or append a formatted run at the end:

// change selected text (if selection is uniform)
if (richTextBox1.SelectionFont != null)
{
    var f = richTextBox1.SelectionFont;
    richTextBox1.SelectionFont = new Font(f.FontFamily, f.Size, f.Style | FontStyle.Bold);
    richTextBox1.SelectionColor = Color.Red;
    richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
}

// append formatted text safely
richTextBox1.SelectionStart = richTextBox1.TextLength;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionFont = new Font("Consolas", 10, FontStyle.Regular);
richTextBox1.SelectionColor = Color.Blue;
richTextBox1.AppendText("Appended formatted line\n");

Gotchas and how to handle mixed formatting

  • SelectionFont will be null when the current selection contains more than one font; SelectionColor returns Color.Empty for mixed colors. Check these before using them. (learn.microsoft.com)
  • To change font across a mixed selection preserve existing sizes/styles by iterating per character (or per run): select one character at a time, read its SelectionFont, then set a new Font based on that. This is the common, reliable workaround community answers use. (stackoverflow.com)

Performance and maintenance tips

  • For many small fragments build an RTF string or use SelectedRtf and assign once — much faster than thousands of per-character selects. Avoid richTextBox.Text += ... because that discards formatting. Reuse Font objects where possible to avoid GDI pressure and do bulk updates inside SuspendLayout/ResumeLayout. (codeproject.com)

If you need WPF instead of WinForms, the APIs differ (use TextRange.ApplyPropertyValue). The examples above are for System.Windows.Forms.RichTextBox.

Recommended Answers

All 2 Replies

Hi Jens,

Many thanks for your help. It's wery helpfull.

regards

Bojan

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.