Reader Level:
ARTICLE

RichTextBox in C#

Posted by Mahesh Chand Articles | Windows Controls C# August 29, 2010
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 demonstrate how to create and use various features of Windows Forms RichTextBox control.
  • 0
  • 0
  • 207912
Download Files:
 

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.

// Create a RichTextBox object

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.

dynamicRichTextBox.Location = new Point(20, 20);

dynamicRichTextBox.Width = 300;

dynamicRichTextBox.Height = 200;

// Set background and foreground

dynamicRichTextBox.BackColor = Color.Red;

dynamicRichTextBox.ForeColor = Color.Blue;

 

dynamicRichTextBox.Text = "I am Dynamic RichTextBox";

dynamicRichTextBox.Name = "DynamicRichTextBox";

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.

 

Controls.Add(dynamicRichTextBox); 

 

A RichTextBox control looks like Figure 1.

RTBImg1.jpg

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.

RTBImg2.jpg

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.

dynamicRichTextBox.Location = new Point(20, 20);

dynamicRichTextBox.Width = 300;

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.

// Set background and foreground

dynamicRichTextBox.BackColor = Color.Red;

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.

dynamicRichTextBox.BorderStyle = BorderStyle.FixedSingle;

Name

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.

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.

dynamicRichTextBox.Text = "I am Dynamic RichTextBox";

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.

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.

RichTextBox1.AppendText(" Appended text");

AcceptsTab

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.

// accepts TAB key

dynamicRichTextBox.AcceptsTab = true;

WordWrap

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.

 

// Wordwrap

dynamicRichTextBox.WordWrap = true;

ScrollBars

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.

dynamicRichTextBox.ScrollBars = RichTextBoxScrollBars.Both;

Font

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.

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.

dynamicRichTextBox.ReadOnly = true;

dynamicRichTextBox.MaxLength = 50;

ReadOnly

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. 

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.

dynamicRichTextBox.ShortcutsEnabled = false;

ShortcutsEnabled property applies to the following shortcut key combinations:

  • CTRL+Z
  • CTRL+E
  • CTRL+C
  • CTRL+Y
  • CTRL+X
  • CTRL+BACKSPACE
  • CTRL+V
  • CTRL+DELETE
  • CTRL+A
  • SHIFT+DELETE
  • CTRL+L
  • SHIFT+INSERT
  • 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.

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.

string [] RichTextBoxLines = dynamicRichTextBox.Lines;

foreach (string line in RichTextBoxLines)

{

    MessageBox.Show(line);

}

Selection in RichTextBox

The SelectedText property returns the selected text in a RichTextBox control.

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.   

dynamicRichTextBox.SelectionStart = 10;

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. 

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.

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (RichTextBox1.TextLength > 0)

        RichTextBox1.SelectAll();

}

 

private void deselectAllToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (RichTextBox1.TextLength > 0)

        RichTextBox1.DeselectAll();

}     

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.

private void cutToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (RichTextBox1.SelectionLength > 0)

        RichTextBox1.Cut();  

}

 

private void copyToolStripMenuItem_Click(object sender, EventArgs e)

{

        if (RichTextBox1.SelectionLength > 0)

            RichTextBox1.Copy();           

}

 

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))

    {

            RichTextBox1.Paste();

    }

}

 

private void undoToolStripMenuItem_Click(object sender, EventArgs e)

{

    if (RichTextBox1.CanUndo)

    {

        RichTextBox1.Undo();

        RichTextBox1.ClearUndo();

    }           

}

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.

private void LoadRTFButton_Click(object sender, EventArgs e)

{

    OpenFileDialog ofd = new OpenFileDialog();

    ofd.InitialDirectory = "c:\\";

    ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

    ofd.FilterIndex = 2;

    ofd.RestoreDirectory = true;

 

    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)

    {

        dynamicRichTextBox.LoadFile(ofd.FileName);

        dynamicRichTextBox.Find("Text", RichTextBoxFinds.MatchCase);

 

        dynamicRichTextBox.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);

        dynamicRichTextBox.SelectionColor = Color.Red;

 

        dynamicRichTextBox.SaveFile(@"C:\Junk\SavedRTF.rtf", RichTextBoxStreamType.RichText);

    }

}

 

BulletIndent

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.

  • <!--[if !supportLists]-->SelectionAlignment – Alignment of selected text.
  • <!--[if !supportLists]--> <!--[endif]-->SelectionBackColor – Background color of selected text.
  • <!--[if !supportLists]--> <!--[endif]-->SelectionBullet – True or false to set if bullets are applied on selected text.
  • <!--[if !supportLists]--> <!--[endif]-->SelectionCharOffset - Whether text in the control appears on the baseline, as a superscript, or as a subscript below the baseline
  • <!--[if !supportLists]--> <!--[endif]-->SelectionColor – Color of selected text.
  • <!--[if !supportLists]-->SelectionFont – Font of selected text.
  • <!--[if !supportLists]--><!--[endif]-->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.
  • <!--[if !supportLists]-->SelectionIndent - Length, in pixels, of the indentation of the line where the selection starts.
  • <!--[if !supportLists]--><!--[endif]-->SelectionProtected - Calue indicating whether the current text selection is protected
  • <!--[if !supportLists]-->SelectionTabs - Absolute tab stop positions.
  • <!--[if !supportLists]-->SelectionType – Selection type represented by RichTextBoxSelectionType enumeration with values Empty, Text, Object, MultiChar, and MultiObject.

The following code snippet sets these selection properties.

private void SelectionButton_Click(object sender, EventArgs e)

{

    dynamicRichTextBox.BackColor = Color.White;

    dynamicRichTextBox.Clear();

 

    dynamicRichTextBox.BulletIndent = 10;

    dynamicRichTextBox.SelectionFont = new Font("Georgia", 16, FontStyle.Bold);

    dynamicRichTextBox.SelectedText = "Mindcracker Network \n";

    dynamicRichTextBox.SelectionFont = new Font("Verdana", 12);

    dynamicRichTextBox.SelectionBullet = true;

    dynamicRichTextBox.SelectionColor = Color.DarkBlue;

    dynamicRichTextBox.SelectedText = "C# Corner" + "\n";

    dynamicRichTextBox.SelectionFont = new Font("Verdana", 12);

    dynamicRichTextBox.SelectionColor = Color.Orange;

    dynamicRichTextBox.SelectedText = "VB.NET Heaven" + "\n";

    dynamicRichTextBox.SelectionFont = new Font("Verdana", 12);

    dynamicRichTextBox.SelectionColor = Color.Green;

    dynamicRichTextBox.SelectedText = ".Longhorn Corner" + "\n";

    dynamicRichTextBox.SelectionColor = Color.Red;

    dynamicRichTextBox.SelectedText = ".NET Heaven" + "\n";

    dynamicRichTextBox.SelectionBullet = false;

    dynamicRichTextBox.SelectionFont = new Font("Tahoma", 10);

    dynamicRichTextBox.SelectionColor = Color.Black;

    dynamicRichTextBox.SelectedText = "This is a list of Mindcracker Network websites.\n";

}

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.

if (dynamicRichTextBox.CanRedo == true)

{

    if (dynamicRichTextBox.RedoActionName != "Delete")

        dynamicRichTextBox.Redo();

}

DetectUrls

If set true, the DetectUrls property will automatically format a Uniform Resource Locator (URL) when it is typed into the control.

EnableAutoDragDrop

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.

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.

private void ZoomButton_Click(object sender, EventArgs e)

{

    dynamicRichTextBox.AutoWordSelection = true;

    dynamicRichTextBox.RightMargin = 5;

    dynamicRichTextBox.ZoomFactor = 3.0f;

}

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. 

Summary
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.

COMMENT USING

Trending up