RichTextBox
A RichTextBox is a multi-line text box that keeps formatting: bold, italic, colour, a font per run of characters, bullets, and links. It is the control behind every small editor a WinForms application has, and it is the one this course's notes capstone uses.
Text with formatting
using System;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
internal sealed class Form1 : Form
{
private readonly RichTextBox _editor = new()
{
Dock = DockStyle.Fill,
DetectUrls = true,
ScrollBars = RichTextBoxScrollBars.Vertical,
WordWrap = true,
};
public Form1()
{
Text = "Notes";
ClientSize = new Size(480, 300);
_editor.LinkClicked += (sender, e) =>
MessageBox.Show(e.LinkText, "A link was clicked");
_editor.AppendText("Release notes" + Environment.NewLine);
_editor.SelectionFont = new Font(_editor.Font, FontStyle.Bold);
_editor.AppendText(Environment.NewLine + "Version 2.1, 2026-11-21" + Environment.NewLine);
_editor.AppendText("See https://example.com/notes for the full text." + Environment.NewLine);
_editor.SelectionColor = Color.SteelBlue;
_editor.AppendText("Written by the editor." + Environment.NewLine);
Controls.Add(_editor);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run, and the ordering of the calls is the whole trick. A RichTextBox applies formatting to the selection at the moment of the change, so AppendText followed by a change of SelectionFont affects the text appended after it, not the text already there. Setting the font before the AppendText that needs it is the pattern; SelectionColor works the same way.
The text appended before the colour change stays black, because SelectionColor was set after it. That sentence reads like a bug in the description and is the behaviour of the control: the properties describe the caret, and the caret is always at the end after AppendText.
The selection
- SelectionStart and SelectionLength: the characters the next formatting call affects, and what a search highlights. Select(start, length) sets both.
- SelectionFont, SelectionColor and SelectionBackColor: the formatting of that span. Reading them when the selection spans two formats gives null for the font, which is the signal that the span is mixed.
- SelectionAlignment, SelectionIndent, SelectionBullet: paragraph-level formatting.
- Find(string) and Find(string, RichTextBoxFinds): a search inside the control that selects the match and returns its index, -1 when there is none. RichTextBoxFinds.Reverse searches upwards, MatchCase makes it case-sensitive.
- CanUndo, Undo and Redo: the control keeps its own undo stack, which is why an editor over it does not need one for typing.
Files and formats
The control reads and writes two formats, and the distinction is the same one the .rtf extension names:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
internal sealed class Form1 : Form
{
private readonly RichTextBox _editor = new() { Dock = DockStyle.Fill };
public Form1()
{
Text = "Open and save";
ClientSize = new Size(460, 280);
var save = new Button { Text = "Save", Dock = DockStyle.Top };
save.Click += (sender, e) => Save("notes.rtf");
Controls.Add(_editor);
Controls.Add(save);
}
private void Save(string path)
{
var format = Path.GetExtension(path) == ".rtf"
? RichTextBoxStreamType.RichText
: RichTextBoxStreamType.PlainText;
_editor.SaveFile(path, format);
}
}
That block is a fragment: a form with no Main, so the checker counts it and does not build it. RichTextBoxStreamType.RichText writes the formatting as RTF, a text format that Word and WordPad also read; PlainText writes the characters and loses every format. LoadFile takes the same enum, and Rtf gives the content as an RTF string for a clipboard or a database column.
Two limits are worth stating. The RTF the control writes is a rich-text interchange format, not a word processor's file: tables and pictures survive in part, and a .docx is not something it opens. And a very large document makes the control slow, because it keeps the whole thing as one formatted buffer; an editor for a hundred-megabyte log uses a TextBox or a virtualised view instead.
Find and replace that runs
The search behind a find bar is string arithmetic, and it is the part of an editor that a test can reach. This program searches a short document, replaces the first match and counts words, and it runs here:
using System;
using System.Collections.Generic;
var text = "Notes on WinForms\nA form owns its controls.\nA form also owns its layout.";
foreach (var match in Find(text, "form"))
{
Console.WriteLine($"match at {match.Index,2}, length {match.Length}");
}
Console.WriteLine($"matches: {Find(text, "form").Count}");
Console.WriteLine(ReplaceFirst(text, "WinForms", "Windows Forms").Split('\n')[0]);
Console.WriteLine($"words: {WordCount(text)}");
static List<(int Index, int Length)> Find(string text, string term)
{
var found = new List<(int Index, int Length)>();
var at = 0;
while (true)
{
var index = text.IndexOf(term, at, StringComparison.OrdinalIgnoreCase);
if (index < 0)
{
return found;
}
found.Add((index, term.Length));
at = index + term.Length;
}
}
static string ReplaceFirst(string text, string term, string replacement)
{
var index = text.IndexOf(term, StringComparison.Ordinal);
return index < 0 ? text : text[..index] + replacement + text[(index + term.Length)..];
}
static int WordCount(string text) =>
text.Split(new[] { ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries).Length;
dotnet run
match at 12, length 4
match at 20, length 4
match at 46, length 4
matches: 3
Notes on Windows Forms
words: 14
The output is the real run, and the first match is the lesson: it is at index 12, inside the word WinForms, because an ordinal search does not know about words. A find bar that should match whole words uses Regex with word boundaries, or checks the characters on both sides of a match; both are in the C# course, in the lesson about regular expressions. The word count is the other half of the same kind of arithmetic, and the split on four separators is what makes a newline count as a boundary.
Exercises
- Make Find skip a match that is inside a longer word, and run the program again. How many matches are left?
- Add a ReplaceAll that returns the text and the number of replacements, and print both.
- Explain from the documentation why setting SelectionFont after AppendText does not format the appended text.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does RichTextBox have that TextBox does not?
Answer
Formatting per run of characters, such as bold and colour
A multi-line TextBox has no per-character formatting; the RichTextBox keeps it.
-
Which pair of properties defines the span a formatting call affects?
Answer
SelectionStart and SelectionLength
Formatting applies to the selection, and Select(start, length) sets it.
-
Why does SelectionFont set after AppendText not format the appended text?
Answer
AppendText leaves the caret at the end, so the change applies to later text
The properties describe the caret, and AppendText moves it to the end.
-
Which stream type keeps the formatting when saving?
Answer
RichTextBoxStreamType.RichText
RichText writes RTF; PlainText writes the characters only.
-
What does DetectUrls do?
Answer
Makes URLs in the text clickable and raises LinkClicked
The control recognises the URL and reports the click with its text.
-
What does Reading SelectionFont return when the selection mixes fonts?
Answer
null
A null font is the signal that the span is not uniform.
-
Why does an editor over a RichTextBox not need its own undo for typing?
Answer
The control keeps CanUndo, Undo and Redo itself
The control has its own undo stack; an application-level undo is for its own commands.
-
What did the run print for the first match of form?
Answer
match at 12, inside WinForms
An ordinal, case-insensitive search finds the substring inside the product name.
-
Why does a whole-word search need more than IndexOf?
Answer
IndexOf does not know where words begin and end
A word boundary is a regular-expression concept, or a check of the neighbouring characters.
-
When is a RichTextBox the wrong control?
Answer
For a very large document that must stay fast
It keeps one formatted buffer, so a huge log needs another view.
Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.
Article author: Arthur Isaev