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

Start

First, this code example shows how the colored text blocks 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 over. We use SelectionBackColor and the AppendText method.

Example that demonstrates RichTextBox: C#

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

namespace WindowsFormsApplication1
{
    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

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.

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

AutoWordSelection

AutoWordSelection can be set to True or False. When 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, this is a useful option.

RichTextBox

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 WindowsFormsApplication1
{
    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

RightMargin

RightMargin is somewhat confusing to use and you will simply have to experiment. The goal is to have some whitespace on the right side of the enclosed text box space. Usually you will not need this property.

RichTextBox

ScrollBars

You can also set the ScrollBars property. 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.

And:In this case, the scrollbar is drawn in a disabled state and cannot be used.

RichTextBox

TextChanged

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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

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

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

Format with buttons

Format

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

Select method call

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 WindowsFormsApplication1
{
    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

1. The characters "Net" are selected.
2. The window text is set to Net.

TextLength

Property

The TextLength property finds out how many characters are present in the RichTextBox. In my testing, this returned the same number as using richTextBox1.Text.Length. Often we can simply take the string length of the Text property.

Copy, Paste

Method

You will find the Copy and Paste methods. There is also a CanPaste boolean method for testing if pasting is possible. Windows Forms programs use the system-wide clipboard, so copied data can be used elsewhere.

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

Question

When should you use the regular TextBox control? 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 better.

TextBox

Summary

We used 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.


C#: Windows