C# RichTextBox

RichTextBox has many formatting options.
It applies colors,
background colors,
multiple fonts,
and margins to the text. It adds more complexity than the regular TextBox. But the RichTextBox provides needed features to programs.

RichTextBox

Example

Note

First, this code example shows how the colored text blocks in the top screenshot were generated in the RichTextBox. In the Form1_Load event, the Font is changed, and then the BackColor is set to a light shade of blue.

Next:Two data arrays are looped through: the SelectionBackColor of the RichTextBox instance is set to the current color, and then the text is appended by invoking AppendText.

Example that demonstrates RichTextBox: C#

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication21
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void Form1_Load(object sender, EventArgs e)
	{
	    richTextBox1.Font = new Font("Consolas", 18f, FontStyle.Bold);
	    richTextBox1.BackColor = Color.AliceBlue;
	    string[] words =
	    {
		"Dot",
		"Net",
		"Perls",
		"is",
		"a",
		"nice",
		"website."
	    };
	    Color[] colors =
	    {
		Color.Aqua,
		Color.CadetBlue,
		Color.Cornsilk,
		Color.Gold,
		Color.HotPink,
		Color.Lavender,
		Color.Moccasin
	    };
	    for (int i = 0; i < words.Length; i++)
	    {
		string word = words[i];
		Color color = colors[i];
		{
		    richTextBox1.SelectionBackColor = color;
		    richTextBox1.AppendText(word);
		    richTextBox1.SelectionBackColor = Color.AliceBlue;
		    richTextBox1.AppendText(" ");
		}
	    }
	}
    }
}

Output of the example
    Please see image at top.

The SelectionBackColor property changes the currently selected text in the RichTextBox to have the background color you assign to it. If there is no current selection, then the caret is used to start the selection. The selection continues for all text appended thereafter.

BackColor

ZoomFactor

One useful property on the RichTextBox control is the ZoomFactor property. Often, you can programmatically set this in another part of your user interface. Alternatively you can set its default value in the Windows Forms designer.

Note:This following screenshot shows the RichTextBox with a ZoomFactor of 3. We see that the text is considerably larger.

RichTextBox and ZoomFactor

AutoWordSelection

Next, we look at another interesting property on the RichTextBox control. This property is the AutoWordSelection property, and it can be set to True or False. When this property is set to True, the selection when the user drags over some text will automatically expand to contain the word being hovered over. If you are focusing on words rather than characters, this is a useful option.

RichTextBox and AutoWordSelection

DetectUrls

When entering text in the RichTextBox, sometimes a link to a web page will be entered. If you set the DetectUrls property to true, the RichTextBox will add hyperlink styles to any possible link. However, if you do not add the LinkClicked event handler, you will not be able to act upon a click.

Here:We simply launch the user's default web browser by passing the clicked URL to Windows.

Example that uses DetectUrls and LinkedClicked: C#

using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication21
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
	{
	    Process.Start(e.LinkText);
	}
    }
}

Result
    Link clicked opens in user's default web browser.

Next, you can see what a hyperlinked text looks like by default in the RichTextBox. When you type in the text, the control itself recognizes the HTTP part of the URL and then highlights it and makes it clickable.

RichTextBox and DetectUrls

RightMargin

The RichTextBox also offers a RightMargin property. This property is somewhat confusing to use and you will simply have to experiment to find the best value. The goal is to have some whitespace on the right side of the enclosed text box space. Usually, you will not need this property, but it is shown here for completeness.

RichTextBox and RightMargin

ScrollBars

You can also set the ScrollBars property on the RichTextBox control. The possible values are None, Horizontal, Vertical, Both, ForcedHorizontal, ForcedVertical, and ForcedBoth. For the forced values, a scrollbar is always displayed even if it is not needed. In this case, the scrollbar is drawn in a disabled state and cannot be used.

RichTextBox and ScrollBars

TextChanged

As with the TextBox control, the RichTextBox control offers a TextChanged event handler. This is a commonly used and useful one. Whenever the text changes for any reason in the RichTextBox, the code in the TextChanged event handler executes.

Next:In this example, we assign the window's title text to the text in the RichTextBox.

Example that uses TextChanged: C#

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication21
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void richTextBox1_TextChanged(object sender, EventArgs e)
	{
	    this.Text = richTextBox1.Text;
	}
    }
}

Output of the example
    Please see screenshot below.

As we see in the following screenshot, this keeps the window's title text in perfect synchronization with the RichTextBox control's contents. You could also detect certain text in the control and perform another action in the event handler based on what you detect.

RichTextBox and TextChanged

Format with buttons

One common requirement for programs that use the RichTextBox is to use a Button control to change the format of the currently selected text. In this way, you can build a program similar to document-based programs like Microsoft Word.

To do this, use the Click event handler on the Button and then set the SelectionColor, SelectionBackColor, or SelectionFont property. You can use the ColorDialog and the Button control for this task.

ColorDialogButton

Select, SelectedText

The RichTextBox also offers the ability to select text based on a starting index and a count of characters, with the Select method. You could use the IndexOf method to search for the location of the text string you want to select.

Also:You can use the SelectedText property to change whatever text is selected, or to find out what text is currently selected.

Example that uses Select and SelectedText: C#

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication21
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void Form1_Load(object sender, EventArgs e)
	{
	    richTextBox1.AppendText("Dot Net Perls");
	    richTextBox1.Select(4, 3);
	    this.Text = richTextBox1.SelectedText;
	}
    }
}

Result of the example
    1. The characters "Net" are selected.
    2. The window text is set to Net.

TextLength

Property

The TextLength property can be used to find out how many characters are present in the RichTextBox. In my testing, this returned the same number as using richTextBox1.Text.Length. Therefore this is probably equivalent in most cases to simply taking the string length of the Text property.

Copy, Paste

You will find the Copy and Paste methods on the RichTextBox instance as well. There is also a CanPaste boolean method for testing if pasting is possible. Windows Forms programs use the system-wide clipboard, so when you invoke Copy, the user will able to use the text in any other program.

And:Parallel to this, Paste will replicate the data from the system clipboard into the RichTextBox.

The RichTextBox offers facilities to undo actions the user has taken in the control. The Undo method is mirrored by the Redo method—these commands are not demonstrated in this article in its current version.

Rtf

Note

RTF stands for Rich Text Format, and this describes a certain file type where text formatting is encoded with special characters embedded in the text. Programs such as Microsoft Word can use RTF documents.

When you apply formatting in a RichTextBox, you can access the richTextBox1.Rtf property to get the encoded RTF data. Please visit Wikipedia for more information about RTF itself and what you can do with it.

Rich Text Format: Wikipedia

TextBox

When should you use the regular TextBox control, and when should you use the fancy RichTextBox? It depends on the goal of your program. If the box is mainly used for entering simple textual data, the TextBox is probably simpler and easier to use.

However:If the box is used to create formatted text documents, such as for posting to a website, then the RichTextBox is definitely better.

TextBox

Summary

We demonstrated how to use the RichTextBox in different ways. You can control the RichTextBox programmatically through C# code, and you can change many properties inside the Visual Studio designer before the program ever executes.

Also:Designed to enable more visual effects than the TextBox, the RichTextBox is used to create RTF documents that are compatible with Microsoft Word.


C#: Windows