RichTextBox in C#

RichTextBox Control

A RichTextBox control is an advanced text box that provides text editing and advanced formatting features including loading rich text format (RTF) files.

In this article, I will demonstrates how to create and use various features of the Windows Forms RichTextBox control.

Creating a RichTextBox

We can create a RichTextBox control using a Forms designer at design-time or using the RichTextBox class in code at run-time.
To create a RichTextBox control at design-time, you simply drag and drop a RichTextBox control from the Toolbox onto a Form in Visual Studio. Once a RichTextBox is added to a Form, you can move it around and resize it using the mouse and set it's properties and events.
Creating a RichTextBox control at run-time is merely a work of creating an instance of RichTextBox class, setting it's properties and adding the RichTextBox object to the Form's Controls collection.
The first step to create a dynamic RichTextBox is to create an instance of the RichTextBox class. The following code snippet creates a RichTextBox control object.
  1. // Create a RichTextBox object  
  3. RichTextBox dynamicRichTextBox = new RichTextBox();  
In the next step, you may set properties of a RichTextBox control. The following code snippet sets size, location, background color, foreground color, Text, Name, and Font properties of a RichTextBox.
  1. dynamicRichTextBox.Location = new Point(20, 20);  
  2. dynamicRichTextBox.Width = 300;  
  3. dynamicRichTextBox.Height = 200;  
  4. // Set background and foreground  
  5. dynamicRichTextBox.BackColor = Color.Red;  
  6. dynamicRichTextBox.ForeColor = Color.Blue;  
  7. dynamicRichTextBox.Text = "I am Dynamic RichTextBox";  
  8. dynamicRichTextBox.Name = "DynamicRichTextBox";  
  9. dynamicRichTextBox.Font = new Font("Georgia", 16);  
Once a RichTextBox control is ready with its properties, the next step is to add the RichTextBox control to the Form. To do so, we use Form.Controls.Add method. The following code snippet adds a RichTextBox control to the current Form.
  1. Controls.Add(dynamicRichTextBox);   
A RichTextBox control looks like Figure 1.
Figure 1

Setting RichTextBox Properties

After you place a RichTextBox control on a Form, the next step is to set properties.
The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2.
Figure 2
Location, Height, Width, and Size
The Location property takes a Point that specifies the starting position of the RichTextBox on a Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a RichTextBox control.
  1. dynamicRichTextBox.Location = new Point(20, 20);  
  2. dynamicRichTextBox.Width = 300;  
  3. dynamicRichTextBox.Height = 200;  
Background, Foreground, BorderStyle
BackColor and ForeColor properties are used to set the background and foreground color of a RichTextBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.
Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.
  1. // Set background and foreground  
  2. dynamicRichTextBox.BackColor = Color.Red;  
  3. dynamicRichTextBox.ForeColor = Color.Blue;  
You can also set the borders style of a RichTextBox by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values – FixedSingle, Fixed3D, and None.  The default value of border style is Fixed3D. The following code snippet sets the border style of a RichTextBox to FixedSingle.
  1. dynamicRichTextBox.BorderStyle = BorderStyle.FixedSingle;  
The Name property represents a unique name of a RichTextBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a RichTextBox control.
  1. dynamicRichTextBox.Name = "DynamicRichTextBox";  
Text and TextLength
The Text property of a RichTextBox represents the current text of a RichTextBox control. The TextLength property returns the length of a RichTextBox contents.
The following code snippet sets the Text and TextAlign properties and gets the size of a RichTextBox control.
  1. dynamicRichTextBox.Text = "I am Dynamic RichTextBox";  
  2. int size = dynamicRichTextBox.TextLength;  
Append Text
One way to append text to a RichTextBox is simply set Text property to current text plus new text you would want to append something like this.
  1. RichTextBox1.Text += " Appended text";  
RichTextBox also has the ApendText method to do the same. The AppendText method appends text at the end of a RichTextBox. The following code snippet uses AppendText method to append text to the RichTextBox1 contents.
  1. RichTextBox1.AppendText(" Appended text");  
If a RichTextBox control is set to multiline, the AcceptsTab property is used to set the RichTextBox control to accept the TAB key as text. If this property is not set, pressing the TAB key simply moves to the next control on the Form. By default, the AcceptsTab property value of a RichTextBox control is false.
  1. // accepts TAB key  
  2. dynamicRichTextBox.AcceptsTab = true;  
If WordWrap property is true, the text in the RichTextBox control automatically wraps to the next line if required. If this property is set to true, horizontal scroll bars are not displayed regardless of the ScrollBars property setting.
  1. // Wordwrap  
  2. dynamicRichTextBox.WordWrap = true;  
A Multiline RichTextBox control can have scrollbars. The ScrollBars property of RichTextBox control is used to show scrollbars on a control. The ScrollBars property is represented by a RichTextBoxScrollBars enumeration that has four values – Both, Vertical, Horizontal, and None.
The following code snippet makes both vertical and horizontal scrollbars active on a RichTextBox control and they will be visible when the scrolling is needed on a RichTextBox control.
  1. dynamicRichTextBox.ScrollBars = RichTextBoxScrollBars.Both;  
Font property represents the font of text of a RichTextBox control. If you click on the Font property in the Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.
  1. dynamicRichTextBox.Font = new Font("Georgia", 16);  
Maximum Length
You can restrict the number of characters in a RichTextBox control by setting MaxLength property. The following code snippet sets the maximum length of a RichTextBox to 50 characters.
  1. dynamicRichTextBox.ReadOnly = true;  
  2. dynamicRichTextBox.MaxLength = 50;  
You can make a RichTextBox control read-only (non-editable) by setting the ReadOnly property to true. The following code snippet sets the ReadOnly property to true. 
  1. dynamicRichTextBox.ReadOnly = true;  
Enabling and Disabling Shortcuts
ShortcutsEnabled property of the RichTextBox is used to enable or disable shortcuts. By default, shortcuts are enabled. The following code snippet disables shortcuts in a RichTextBox.
  1. dynamicRichTextBox.ShortcutsEnabled = false;  
ShortcutsEnabled property applies to the following shortcut key combinations:
  • CTRL+Z
  • CTRL+E
  • CTRL+C
  • CTRL+Y
  • CTRL+X
  • CTRL+V
  • CTRL+A
  • CTRL+L
  • CTRL+R
Read RichTextBox Contents
The simplest way of reading a RichTextBox control contents is using the Text property. Note however that the Text property has no formatting; it has only text. See the Rtf property for the text including the formatting. The following code snippet reads contents of a RichTextBox in a string.
  1. string RichTextBoxContents = dynamicRichTextBox.Text;  
In a multiline RichTextBox, if the RichTextBox contents are separated by multiple lines and you want to read contents of a RichTextBox line by line, you can use the Lines property of the RichTextBox. The Lines property returns an array of strings where each element of the returned array is a line.
The following code snippet reads a RichTextBox contents line by line.
  1. string [] RichTextBoxLines = dynamicRichTextBox.Lines;  
  2. foreach (string line in RichTextBoxLines)  
  3. {  
  4.     MessageBox.Show(line);  
  5. }  
Selection in RichTextBox
The SelectedText property returns the selected text in a RichTextBox control.
  1. string selectedText = dynamicRichTextBox.SelectedText;  
You may also use SelectionStart and SelectionLength properties to get and set the selected text in a RichTextBox. The SelectionStart property represents the starting index of the selected text and SelectionLength property represents the number of characters to be selected after the starting character. The following code snippet sets the selection on a RichTextBox.   
  1. dynamicRichTextBox.SelectionStart = 10;  
  2. dynamicRichTextBox.SelectionLength = 20;  
Clear, SelectAll and DeselectAll
The Clear method removes the contents of a RichTextBox. The following code snippet uses Clear method to clear the contents of a RichTextBox. 
  1. RichTextBox1.Clear();  
RichTextBox class provides SelectAll and DeselectAll methods to select and deselect all text of a RichTextBox control. The following code snippet shows how to use SelectAll and DeselectAll methods.
  1. private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)  
  2. {  
  3.     if (RichTextBox1.TextLength > 0)  
  4.         RichTextBox1.SelectAll();  
  5. }  
  7. private void deselectAllToolStripMenuItem_Click(object sender, EventArgs e)  
  8. {  
  9.     if (RichTextBox1.TextLength > 0)  
  10.         RichTextBox1.DeselectAll();  
  11. }    
Cut, Copy, Paste, Undo Operations in RichTextBox
RichTextBox class provides Cut, Copy, Paste, and Undo methods to cut, copy, paste, and undo clipboard operations. The following code snippet shows how to use Cut, Copy, Paste, and Undo methods.
  1. private void cutToolStripMenuItem_Click(object sender, EventArgs e)  
  2. {  
  3.     if (RichTextBox1.SelectionLength > 0)  
  4.         RichTextBox1.Cut();    
  5. }  
  7. private void copyToolStripMenuItem_Click(object sender, EventArgs e)  
  8. {  
  9.         if (RichTextBox1.SelectionLength > 0)  
  10.             RichTextBox1.Copy();             
  11. }  
  13. private void pasteToolStripMenuItem_Click(object sender, EventArgs e)  
  14. {  
  15.     if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))  
  16.     {  
  17.         RichTextBox1.Paste();  
  18.     }  
  19. }  
  21. private void undoToolStripMenuItem_Click(object sender, EventArgs e)  
  22. {  
  23.     if (RichTextBox1.CanUndo)  
  24.     {  
  25.         RichTextBox1.Undo();  
  26.         RichTextBox1.ClearUndo();  
  27.     }             
  28. }  
Load and Save RTF Files
LoadFile method of RichTextBox control is used to load an RTF file and displays its contents. SaveFile method is used to save the contents of a RichTextBox to an RTF file. The following code snippet loads an RTF file using an OpenFileDialog and saves back its contents.
  1. private void LoadRTFButton_Click(object sender, EventArgs e)  
  2. {  
  3.     OpenFileDialog ofd = new OpenFileDialog();  
  4.     ofd.InitialDirectory = "c:\\";  
  5.     ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";  
  6.     ofd.FilterIndex = 2;  
  7.     ofd.RestoreDirectory = true;  
  8.     if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  9.     {  
  10.         dynamicRichTextBox.LoadFile(ofd.FileName);  
  11.         dynamicRichTextBox.Find("Text", RichTextBoxFinds.MatchCase);  
  12.         dynamicRichTextBox.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);  
  13.         dynamicRichTextBox.SelectionColor = Color.Red;  
  14.         dynamicRichTextBox.SaveFile(@"C:\Junk\SavedRTF.rtf", RichTextBoxStreamType.RichText);  
  15.     }  
  16. }  
BulletIndent property gets or sets the indentation used in the RichTextBox control when the bullet style is applied to the text.
dynamicRichTextBox.BulletIndent = 10;
Selection Properties
Here is a list of properties that are applicable on current selected text.
  • SelectionAlignment - Alignment of selected text.
  • SelectionBackColor - Background color of selected text.
  • SelectionBullet - True or false to set if bullets are applied on selected text.
  • SelectionCharOffset - Whether text in the control appears on the baseline, as a superscript, or as a subscript below the baseline
  • SelectionColor - Color of selected text.
  • SelectionFont - Font of selected text.
  • SelectionHangingIndent - Distance between the left edge of the first line of text in the selected paragraph and the left edge of subsequent lines in the same paragraph.
  • SelectionIndent - Length, in pixels, of the indentation of the line where the selection starts.
  • SelectionProtected - Calue indicating whether the current text selection is protected
  • SelectionTabs - Absolute tab stop positions.
  • SelectionType - Selection type represented by RichTextBoxSelectionType enumeration with values Empty, Text, Object, MultiChar, and MultiObject.
The following code snippet sets these selection properties.
  1. private void SelectionButton_Click(object sender, EventArgs e)  
  2. {  
  3.     dynamicRichTextBox.BackColor = Color.White;  
  4.     dynamicRichTextBox.Clear();  
  5.     dynamicRichTextBox.BulletIndent = 10;  
  6.     dynamicRichTextBox.SelectionFont = new Font("Georgia", 16, FontStyle.Bold);  
  7.     dynamicRichTextBox.SelectedText = "Mindcracker Network \n";  
  8.     dynamicRichTextBox.SelectionFont = new Font("Verdana", 12);  
  9.     dynamicRichTextBox.SelectionBullet = true;  
  10.     dynamicRichTextBox.SelectionColor = Color.DarkBlue;  
  11.     dynamicRichTextBox.SelectedText = "C# Corner" + "\n";  
  12.     dynamicRichTextBox.SelectionFont = new Font("Verdana", 12);  
  13.     dynamicRichTextBox.SelectionColor = Color.Orange;  
  14.     dynamicRichTextBox.SelectedText = "VB.NET Heaven" + "\n";  
  15.     dynamicRichTextBox.SelectionFont = new Font("Verdana", 12);  
  16.     dynamicRichTextBox.SelectionColor = Color.Green;  
  17.     dynamicRichTextBox.SelectedText = ".Longhorn Corner" + "\n";  
  18.     dynamicRichTextBox.SelectionColor = Color.Red;  
  19.     dynamicRichTextBox.SelectedText = ".NET Heaven" + "\n";  
  20.     dynamicRichTextBox.SelectionBullet = false;  
  21.     dynamicRichTextBox.SelectionFont = new Font("Tahoma", 10);  
  22.     dynamicRichTextBox.SelectionColor = Color.Black;  
  23.     dynamicRichTextBox.SelectedText = "This is a list of Mindcracker Network websites.\n";  
  24. }  
The output text in a RichTextBox looks like Figure.
Redo and CanRedo
Redo method can be used to reapply the last undo operation to the control.
CanRedo property represents whether there are actions that have occurred within the RichTextBox that can be reapplied.
  1. if (dynamicRichTextBox.CanRedo == true)  
  2. {  
  3.     if (dynamicRichTextBox.RedoActionName != "Delete")  
  4.         dynamicRichTextBox.Redo();  
  5. }  
If set true, the DetectUrls property will automatically format a Uniform Resource Locator (URL) when it is typed into the control.
RichTextBox control supports drag and drop operations that allow us to drag and drop text, picture, and other data. EnableAutoDragDrop property enables drag-and-drop operations on text, pictures, and other data.
  1. dynamicRichTextBox.EnableAutoDragDrop = true;  
RightMargin, AutoWordSelection, and ZoomFactor
RightMargin property represents the size of a single line of text within a RichTextBox control.
AutoWordSelection property represents if a word is automatically selected when a text is double clicked within a RichTextBox control.
ZoomFactor represents the current zoom level of the RichTextBox. Value 1.0 means there is no zoom applied on a control.
  1. private void ZoomButton_Click(object sender, EventArgs e)  
  2. {  
  3.     dynamicRichTextBox.AutoWordSelection = true;  
  4.     dynamicRichTextBox.RightMargin = 5;  
  5.     dynamicRichTextBox.ZoomFactor = 3.0f;  
  6. }  
Rtf and SelectedRtf
Rtf property is used to get and set rich text format (RTF) text in a RichTextBox control. SelectedRtf property is used to get and set selected text in a control. RTF text is the text that includes formatting. 


A RichTextBox control accepts user input on a Form and provides rich text features. In this article, we discussed discuss how to create a RichTextBox control in Windows Forms at design-time as well as run-time. After that, we saw how to use various properties and methods.
Further Readings

Here is a list of more articles related to this topic.

Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.