1. Introduction to C# RichTextBox Control
Just like text box C# RichTextBox also a similar control, which takes text input in the form of ‘Rich Text’. What is the difference between typing a three-page document in notepad application and in WordPad application? Are you piling up with the differences? The difference that came in your mind is the difference between the ‘TextBox’ versus ‘RichTextBox’. This means unlike the typical Text box, in the RichTextBox we can mark the piece of the text and set unique aspects like bold, italic, text color, etc.
We can save and load the C# RichTextBox content into a physical disc in two formats. One is a ‘Plain Text (TXT format)’ format and the other one is ‘Rich Text Format (RTF format)’. In this article, we will have a look at the basic usage of the RichTextBox control.
2. About the C# RichTextBox Example
Below is the screenshot of the sample application for the example:

C# RichTextBox Control Example
In this example, we can type the text content in the left-hand-side text area. Also, we can perform some basic operation on the typed content through the right-hand side Controls of the dialog.
2.1 Plain Text vs Rich Text
The control on the left-side of the dialog is called C# RichTextBox. This control supports Plain text and Rich Text. The Plain text will not have any property like bold text, text color or even configurable fonts with color and size. We may ask that the notepad is a utility supplied by windows that support plain text. But I can change the Font and Font Size. What we should know is that the Font or Font size is applied to the complete document and when we save plain text the change in the font not saved to the disc. That means plain text is still plain text. But the notepad (text viewer) applied the font change temporarily. If some other person opens the saved content from the disc, they may see a different text font their notepad configuration.
Rich text can hold a variety of properties with them. When you save the rich text, those properties also saved in the disc along with the text content. What property we are talking about? Well, it is like font colors, Italic, text size, etc. So whoever open the document, they see same text formatting.
2.2 Formatting Rich Text
We divide the sample into two panels. The left side panel has big RichTextBox Control for typing the text contents. Right side panel has three action buttons and using those we can perform various formatting operations on the typed content. We can save and load the document by clicking the corresponding button on the right-hand side action panel. We can change the text format by using the controls on section 2 of the panel. In this example, we can set Bold, Italic, Underline, Font and Font size to the text contents. But rich text supports much more such properties. We have picked those basic ones for demonstration. One can also try with formatting the text with colors.
2.3 Copy, Paste, Undo and Redo
The Normal text box supports copy and paste by default (Rich click on it). But rich text box does not provide that function by default. In section 3 of our Window Form, we can perform Copy and Paste clipboard operation. Also, here we can perform Undo and Redo actions.
Undo will dismiss the effect of our last operation. Say, for example, let us say, we did the following operation in a sequence on the Rich text content:
- Typed a some line of Texts
- Applied a Font for it
- Then Changed the Font Size
Now the two consecutive Undo will cancel the effect of Font and Font size in the rich text content. The Redo option will cancel the last Undo Operation.
3. Preparing the Form
We place two panels on the Form. We dock the first panel to the right of the Form and resized enough to support the buttons and other controls on the right. In our example, the RichTextBox occupies the full area on the left side. To do this, we place the C# RichTextBox Control in the left panel and set its Dock property to fill. Below are details:
- Form Place Holder for the two panels.
- Left Panel’s ‘Dock Property’ set to ‘Left’ and it holds all the action buttons.
- Right Panel’s dock property set to ‘Fill’ and holds only the RichTextBox control in it.
- RichTextBox is placed on the Right side panel, and its dock property is set to Fill.
Note that the Left-Side panel is filled in the remaining portion of the form. The remaining portion is the space left after housing the controls in the Right-Side Panel. The RichTextBox fills the entire area of the Left Side Panel. The video in this section shows the form preparation.
Video Steps & Video
- First, we add a Panel to the form. Then, we dock it to the right-side edge of the form.
- Then the panel is resized. The right-side panel will have all the command for the rich text box sample.
- Next we add one more panel to the left of the command panel.
- This panel is asked to fill the remaining area. Later we place the C# RichTextBox Control in it.
You can design form as shown in the above picture. To set properties, download the example at the end of this article and use it as reference.
4. Saving the C# RichTextBox Content
The ‘
<strong>SaveFile()</strong> Method
’ of the C# RichTextBox control allows saving the RichTextBox content in two formats. One is plain text (.txt) and the other one is Rich text format (.rtf). We will pass the stream type to the above-said method specifying the format in which we want to save the data. Our example uses ‘
SaveFileDialog
’ to pick a filename, and before displaying the dialog, we set the filter types to *.txt and *.rtf. Below is the code for saving RichTextBox data. The RichTextBox enumeration type ‘
RichTextBoxStreamType
’ is set to plain or rich based on the Filter type in the
SaveFileDialog
.
Below is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
//Richtext 01: Save Rich Text file context private void btnSave_Click(object sender, EventArgs e) { //Richtext 01_01: Create the Save File dialog Instance SaveFileDialog saveDlg = new SaveFileDialog(); string filename = ""; //Richtext 01_02: Set the Filters for the save dialog. //Don't include space when typing *.ext. Because space is //treated as extension saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt"; saveDlg.DefaultExt = "*.rtf"; saveDlg.FilterIndex = 1; saveDlg.Title = "Save the contents"; //Richtext 01_03: Show the save file dialog DialogResult retval = saveDlg.ShowDialog(); if (retval == DialogResult.OK) filename = saveDlg.FileName; else return; //Richtext 01_04: Set the correct //stream type (Rich text or Plain text?) RichTextBoxStreamType stream_type; if (saveDlg.FilterIndex == 2) stream_type = RichTextBoxStreamType.PlainText; else stream_type = RichTextBoxStreamType.RichText; //Richtext 01_05: Now its time to save the content RT.SaveFile(filename, stream_type); } |
The below video shows saving the Rich Text box content in a Plain text document.
Video Steps
- In the RichTextBox, first we type three lines of texts.
- Then we save the RichTextBox content in plain text format (.txt)
- We open the saved content with the notepad as it understands the plain text format.
5. Loading C# RichTextBox Content
The code implemented for loading the saved text looks like the event handler for save button click. Below are the exceptions.
- In place of using the SaveFileDialog, ‘Load Click Handler’ uses the OpenFileDialog.
- ‘ LoadFile() Method’ of the RichTextBox is called to load the file from the disc.
Below is the Code for loading the text file content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
//Richtext 02: Open the Plain or Rich Text content private void btnLoad_Click(object sender, EventArgs e) { //Richtext 02_01: Create instance of Open file dialog OpenFileDialog file_open = new OpenFileDialog(); //Richtext 02_02: Setup open file dialog before displaying it file_open.Filter = "Rich Text File (*.rtf)|*.rtf| Plain Text File (*.txt)|*.txt"; file_open.FilterIndex = 1; file_open.Title = "Open text or RTF file"; //Richtext 02_03: Display the dialog and grab the file name RichTextBoxStreamType stream_type; stream_type = RichTextBoxStreamType.RichText; if (DialogResult.OK == file_open.ShowDialog()) { //Richtext 02_04: Set the correct stream type //(Rich text or Plain text?) if (string.IsNullOrEmpty(file_open.FileName)) return; if (file_open.FilterIndex == 2) stream_type = RichTextBoxStreamType.PlainText; //Richtext 02_05: Open the content of the selected file RT.LoadFile(file_open.FileName, stream_type); } } |
Loading the already saved text content is shown in the below video.
Video Steps
- First, we Load the plain text content saved in the previous video.
- The video shows the loaded content in the RichTextBox control.
6. Set RichTextBox’s Bold, Italic, Underline Using SelectionFont
C# RichTextBox allows formatting the portion of the text in bold, Italic and Underlined. The capability of setting these kinds of attributes makes it different from the normal text box. Have a look at the below piece of code:
1 2 3 4 |
Font SelectedText_Font = RT.SelectionFont; if (SelectedText_Font != null) RT.SelectionFont = new Font(SelectedText_Font, SelectedText_Font.Style ^ FontStyle.Bold); |
The code above changes the selected text to Bold style. First, we had taken the Font object of the selected text by making use of the ‘SelectionFont Property’ of the RichTextBox. Then a new font is constructed using the existing font returned by the SelectionFont property. During the construction, we used the Bit-wise XOR operation (
SelectedText_Font.Style ^ FontStyle.Bold
) to negate the Bold style. This means if the selected font has bold property set, clicking the Bold button again will remove the Bold Style from the Font.
Below is the Full Code for Bold, Italic and Underline:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
//Richtext 03: Set Bold, Italic and Underline Styles to the //Selection. First get the Font name from the selection and then //apply the specific style. private void btnBold_Click(object sender, EventArgs e) { Font SelectedText_Font = RT.SelectionFont; if (SelectedText_Font != null) RT.SelectionFont = new Font(SelectedText_Font, SelectedText_Font.Style ^ FontStyle.Bold); } private void btnItalic_Click(object sender, EventArgs e) { Font SelectedText_Font = RT.SelectionFont; if (SelectedText_Font != null) RT.SelectionFont = new Font(SelectedText_Font, SelectedText_Font.Style ^ FontStyle.Italic ); } private void btnUnderline_Click(object sender, EventArgs e) { Font SelectedText_Font = RT.SelectionFont; if (SelectedText_Font != null) RT.SelectionFont = new Font(SelectedText_Font, SelectedText_Font.Style ^ FontStyle.Underline ); } |
The below video shows how we apply bold and italic font style to specific text in the Rich Text:
Video Steps
- First, we load the text file from the disc.
- Next we apply bold, italic and underline style to some portion of the text.
- Then we save the result in Rich text format. (Note plain text won’t support text attributes for different portions of the text)
- Finally, we load the Rich Text content and check it shows text attributes applied in the previous step.
7. Setting RichTextBox Font Style and Size
It has more work to do. First, we should load the ‘System Fonts’ to a combo box shown in the sample app screen shot. Then we should load the ‘Font Sizes’ in another combo box. Then regardless of whether user changed the combo box selection for Font or Font Size, we will re-construct the Font Object and set it to the selected text in the C# RichTextBox. Since both the combo boxes’ selection changed event does a similar job, we will write a custom function and call that for both the combo boxes.
7.1 Load Font Name in Combo Box
In the Form Load handler, we iterate the font families through the FontFamily Array returned by the ‘
GetFamilies()
’ static method of ‘
FontFamily Class
’. The method takes a Graphic object and we get the Graphics object linked to the RichTextBox by calling the function ‘
CreateGraphics()
’. Once we have the Font Family name, we add the name to the Font Combo box. Below is the code for it:
1 2 3 4 5 6 7 |
//04_1: Get all the Font Family names from the Graphics associated //to Rich text box. Then load the font name to combo box Graphics gr = RT.CreateGraphics(); foreach (FontFamily F_family in FontFamily.GetFamilies(gr)) { cmbFont.Items.Add(F_family.Name); } |
Next, we populate the numeric values in the Font size ComboBox. Below is the code, which does not require any explanation:
1 2 3 |
//04_2: Load the Font Sizes for (int fsize = 7; fsize < 73; fsize++) cmbFontSize.Items.Add(fsize); |
7.2 Collect Selected Text’s Font Details
The ‘
SetNewFont
’ function is written to change the font and font size of the selected text. Below is the Declaration required for the task:
1 2 3 4 5 6 7 |
//Richtext 05_01: Declarations that will feed Font Ctor Font old_font; Font new_font; String FName; float FSize = 8; FontStyle style = 0; byte charset = 0; |
We set the
FSize
variable with a more recent font size. To do that, we read the selected text from the font size ComboBox. When the user does not pick any font size from the ComboBox, we assign a default font size of 8. Also, we are storing the current font of the selected text in
old_font
.
1 2 3 4 5 6 7 |
//Richtext 05_02: Grab required information from UI FName = cmbFont.Text; if (string.IsNullOrEmpty(cmbFontSize.Text)) FSize = 8; else FSize = float.Parse(cmbFontSize.Text); old_font = RT.SelectionFont; |
Next, we store the font style and GDI Character Set from the existing font. The constructor of the Font class will use all the data we are collecting here. Below is the Code:
1 2 3 4 5 6 7 8 9 10 |
//Richtext 05_03: Treat the situation of no font/selection text if (old_font == null) { style = FontStyle.Regular; } else { style = old_font.Style; charset = old_font.GdiCharSet; } |
7.3 Set New Font
Now we have all data required for the new font. So, we construct the Font instance and set that instance as the current selection font. The Function ends here. Below is the code for it:
1 2 3 4 5 6 7 8 9 |
//Richtext 05_04: All the parameters for the ctor is ready. //Construct the Font new_font = new Font( FName, FSize, style, GraphicsUnit.Point, charset); RT.SelectionFont = new_font; |
Note that all the information passed to the constructor is given a default value or collected from the existing font of the selected text. Finally, we call the
SetNewFont
function from ‘
SelectedIndexChanged
Event’ Handler of both the Combo Boxes. Below is the code:
1 2 3 4 5 6 7 8 9 |
//Richtext 06: Set the font to the selection when either font name or font size changed private void cmbFont_SelectedIndexChanged(object sender, EventArgs e) { SetNewFont(); } private void cmbFontSize_SelectedIndexChanged(object sender, EventArgs e) { SetNewFont(); } |
Below video shows setting different font and font size to a single line of text in RichTextBox control.
Video Steps
- First we loads already saved plain text.
- Then we select the second line of text.
- And applies different font and font style.
- Finally we save the content and reload it for a cross check.
8. Copy, Paste, Undo and Redo
C# RichTextBox gives all the functionality stated in the title as member functions. So the Click event handler on the form for tasks copy, paste, Undo and Redo will simply call the related member function of the C# RichTextBox. Below is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//Richtext 07: Other baisc functionality of Richtext box private void btnCopy_Click(object sender, EventArgs e) { RT.Copy(); } private void btnPaste_Click(object sender, EventArgs e) { RT.Paste(); } private void btnUndo_Click(object sender, EventArgs e) { RT.Undo(); } private void btnRedo_Click(object sender, EventArgs e) { RT.Redo(); } private void btnClear_Click(object sender, EventArgs e) { RT.Clear(); } |
Below video shows the clipboard operation on Rich Text. It also shows the use of undo and redo option on RichTextBox Control.
Video Steps
- The video copies #using statements from Source file.
- Then pastes the content to the rich text box.
- From the pasted content, copies some portion of text to clipboard.
- Opens the WordPad application and pastes it.
- Finally applied some attributes and shows the undo and redo options.
Source Code: Download the C# RichTextBox Example From Google Drive
Categories: C#
Tags: CreateGraphics(), LoadFile(), OpenFileDialog, Redo, Rich Text, RichTextBoxStreamType, SaveFile(), SaveFileDialog, SelectionFont, Undo
This was supper helpful. Gave me just want i wanted.Thanks.