C# RichTextBox Control

The RichTextBox control (System.Windows.Forms.RichTextBox) is similar to a TextBox control, but it allows you to format different parts of the text inside it. The TextBox control is typically used to accept text input from the user while the RichTextBox control is used to show formatted text and save it in Rich Text Format (RTF).

RichTextBox
RichTextBox

Figure 1

Figure 1 shows a difference between a TextBox(top) and a RichTextBox(bottom) controls. Although you can do formatting in a normal text box, it is always applied to all of the text inside it. The RichTextBox control allows you to format parts of the whole text of the control. You can also use a rich text box control to accept input from the user as both TextBox and RichTextBox are derived from TextBoxBase class, therefore, they share the most common properties such as the Text property.

The following are some common properties available when using the RichTextBox control.

Property Description
AcceptsTab Specifies whether to accept focus as a result of pressing the tab key.
BulletIndent Specifies the indentation utilized in the RichTextBox control once the bullet vogue is applied to the text.
CanRedo Specifies a whether there are actions that have occurred within the RichTextBox that can be reapplied.
CanUndo Specifies whether or not the user will undo the operations worn out a RichTextBox control.
DetectUrls Specifies whether to automatically detect and add the target link to URLs inside the RichTextBox control.
Lines A collection of individual lines in a RichTextBox control.
Modified Tells whether the contents of the RichTextBox control has been modified since the last time it was set.
Multiline Tells whether the RichTextBox control can have multiple lines of text (true by default).
ReadOnly Tells whether the RichTextBox control is read-only.
RedoActionName Specifies the name of the action than can be redone once an undo operation is made and the Redo method is called.
Rtf Contains the text of the RichTextBox control including the rich text format (RTF) codes.
Scrollbars Specifies the type of scrollbars to display.
SelectedRtf Gets or sets the presently elect made text format (RTF) formatted text within the management.
SelectedText Gets or sets the chose message inside the RichTextBox.
SelectionAlignment Specifies the alignment to use to this choice or insertion purpose.
SelectionBackColor Determines the foundation shade of the chose content.
SelectionBullet Specifies whether or not the bullet vogue is applied to the present choice or insertion purpose.
SelectionCharOffset Specifies whether the selected text in the control appears on the baseline, as a superscript, or as a subscript below the baseline.
SelectionColor Specifies the color of the selected text.
SelectionFont Specifies the font that the selected text will use.
SelectionLength Specifies the number of characters of the selected text.
SelectionProtected Tells whether the selected text or all the text after the insertion point is protected.
SelectionRightIndent The distance (in pixels) between the correct fringe of the RichTextBox control and therefore the right fringe of the text that’s chosen or further at the present insertion purpose.
SelectionStart Specifies the starting position of the selection or the insertion point.
ShortcutsEnabled Specifies whether predefined or defined shortcut keys is enabled.
ShowSelectionMargin Specifies whether a selection margin is displayed in the RichTextBox.
Text The plain text inside the RichTextBox control.
UndoActionName Specifies the action that can be undone in the control when the Undo method is called.
WordWrap Specifies whether to wrap the text inside the RichTextBox control.

Figure 2 – RichTextBox Properties

The following are some events that you can handle for the RichTextBox control.

Event Description
LinkClicked Occurs when a link was clicked.
Protected Occurs when the user attempts to modify a protected text.
TextChanged Occurs when the text inside the RichTextBox is modified.
SelectionChanged Occurs when the selected text is changed.

Figure 3 – RichTextBox Events

Changing Format of the Selected Text

A lot of the properties of the RichTextBox control is used for the currently selected text. For example, the SelectedText specifies the currently selected text by the user. You can also use the Select method to select texts.

richTextBox1.Select(10, 11);
RichTextBox
RichTextBox

The first parameter specifies the starting index of the selection and the second parameter specifies the length of the selection starting from the starting index.

Once we have selected a text, we can format the selected text using more properties that focus on the current selection. For example, to change the color of the currently selected text, you can use the SelectionColor property or the SelectionBackColor to change its background color.

richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectionBackColor = Color.Yellow;

You can then deselect the selected text by clicking anywhere in the form or by using the DeselectAll method.

richTextBox1.DeselectAll(); 

Please note that when no text is selected, the effect of the selection properties starts from the insertion point. The insertion point is simply the location of the blinking I-beam which specifies the insertion of text will start there. Every new character that you type will now receive the new format you have specified.

Adding A Selection Margin


The selection margin is the little margin on the left side of the RichTextBox control.

The selection margin (indicated by the arrow) is used to easily select a single line of text. For example, the screenshot above shows the third line selected by clicking the selection margin space beside it. We can set the SelectionMargin property of the RichTextBox control to show the selection margin.

Adding Scrollbars


To add scrollbars, we use the ScrollBars property which accepts a value from the RichTextBoxScrollBars enumeration. This enumeration contains values Horizontal, which adds a horizontal scrollbar when the length of the line is too long and the WordWrapproperty is set to false; Vertical, which adds a vertical scrollbar when the number of lines of text doesn’t fit the height of the RichTextBox; and Both, which automatically adds horizontal and vertical scroll bar when necessary. When the SelectionMargin property is set to false, you need to use a different set of enumeration values, ForcedHorizontalForcedVertical, and ForcedBoth. To disable scrollbars completely, set it RichTextBoxScrollBars.None.

Changing Alignment of Selected Text


We can use the SelectionAlignment property to change the alignment of the selected text, more properly, the paragraph where the selected text or the insertion point is located. The property accepts a value from the HorizontalAlignment enumeration which includes LeftRight, and Center. It is important to know how paragraphs are made inside the control. Initialily, typing your the first character to the rich text box will create a paragraph. To create the next paragraph, you simply press the Enter or Return key.

Undoing and Redoing


You can specify whether the user can undo or redo operation using the CanUndo and CanRedo properties. Undoing simply reverts the change you have done to the contents of the RichTextBox control while redoing negates the effect of undo and brings back the change you have made to the content. The properties UndoActionName and RedoActionName are used to restrict the undo and redo operation to specific actions only. These properties accepts actions in form of strings. The possible actions are:

Action Description
Typing Typing operation
Delete Delete operation
DragDrop Drag and Drop operation
Cut Cut operation
Paste Paste operation

For example, you can assign the string “Delete” to the UndoActionName property to only allow the user to undo a delete operation.

richTextBox1.UndoActionName = "Delete";

For an unknown reason, Microsoft did not make an enumeration for these properties so you have to strings as actions.

Detecting URL’s


The RichTextBox control has the capability to automatically detect URL’s that are typed or pasted to the control. The DetectUrlsproperty allows the control to automatically detect url’s and create a link to their target web page. Setting that property to true activates the feature and setting it to false deactivates it. Shown in the image below, you can see that URL’s to website resemble a link and putting your mouse cursor over them will change the cursor to a hand.

Clicking the link opens the website using your default web browser.

Adding Bullets


You can create bullets inside a RichTextBox control. You use the SelectionBullet property and set it to faithful indicate that the chosen text ought to became buletted text. The BulletIndent property specifies the distance between the bullet and the starting position of the text. The program below has a button that adds a bullet to the beginning of each selected line, or paragraph or to where the insertion piont is located.

RichTextBox
RichTextBox

Enabling and Disabling Shortcut Keys


The ShortcutsEnabled property enables or disables shortcut keys such as those for cutting and pasting text to the text box. When this is set to true, the following shortcut keys will be accepted by the RichTextBox control.

Shortcut Function
Ctrl + Z Undo
Ctrl + E Center Alignment of Text
Ctrl + C Copy
Ctrl + Y Redo
Ctrl + X Cut
Ctrl + Backspace Deletes an entire word to the left of cursor.
Ctrl + V Paste
Ctrl + Delete Deletes an entire word to the right of the cursor.
Ctrl + A Select All Text
Ctrl + L Left Justify
Ctrl + R Right Justify

Setting ShortcutEanbled to false disables these shortcuts.

Protecting Texts


You have the ability to protect certiain parts of text using the SelectionProtected property which when set to true, protects the currently selected text. A protected text cannot be modifies. When the user tries to modify a protected text, then teh Protected event will trigger. You can handle this event to, for example, show a message telling the user that the text he is trying to modify is protected.

Rich Text Format (RTF)


The Rich Text Format is a document file format that remembers the formatting of your text or document. The normal TextBox control cannot save text formats because it simply contains plain text. The RichTextBox control has the Text and Rtf properties where the Text property contains the plain text of the control while the Rtf property contains the text and the RTF codes used to format the text. The screenshots below show you the formatted text, and the RTF codes behind that formatted text.

The RTF code allows other programs (such as Word) to read the formatting and present to you the formatted text. The SelectedRtfgets the selected text together with the RTF codes associated to it. This allows you to include the format when cutting and pasting formatted texts.