RichTextBox Styles

Posted Sat, Oct 31 2009 22:42 by Deborah Kurata

If you are building a WinForms application and want to style your text, you may want to use the RichTextBox control instead of the standard TextBox control. This post provides some of the common techniques required to style text in a RichTextBox control.

To try out the examples in this post, build a new WinForms application. If desired, change the name of the form to "RichTextBoxSampleWin". Add a RichTextBox and two buttons to the form.

Setting Fonts/Colors

To set the fonts and colors of a RichTextBox, always select the text to style first, then set its font and color.

To try out setting fonts and colors, add this code to the Load event for the form:

In C#:

richTextBox1.Text = "That that is, is. That that is not, is not. "
                               + "Is that it? It is.";

// Set the style of the text
richTextBox1.SelectionLength = richTextBox1.Text.Length;
richTextBox1.SelectionFont = new Font("Arial", 12, FontStyle.Bold);
richTextBox1.SelectionColor = Color.DarkSlateBlue;
richTextBox1.SelectionStart = richTextBox1.Text.Length;

In VB:

richTextBox1.Text = "That that is, is. That that is not, is not. " & _
                                               "Is that it? It is."

' Set the style of the text
richTextBox1.SelectionLength = richTextBox1.Text.Length
richTextBox1.SelectionFont = New Font("Arial", 12, FontStyle.Bold)
richTextBox1.SelectionColor = Color.DarkSlateBlue
richTextBox1.SelectionStart = richTextBox1.Text.Length

The first line of code sets text into the RichTextBox.

The most important step here is to select the text that you want to style. Use the SelectionStart property to set the location in the text string to start the selection. If you don't specify a selection start, it is assumed to start at the first character of the text. Use the SelectionLength property to specify the length of the selection. In this case, the entire length of text is selected to be styled.

NOTE: Instead of setting the SelectionStart and SelectionLength properties, you can use the Select method to set both the selection start and selection length at one time.

The next two lines set the font and color for the selected text. The last line resets the SelectionStart to the end of the text. This allows the user to type in further text.

If you run the application at this point, it should look like this:

image

If the user types in more text, it will follow the given style.

Setting Multiple Fonts/Colors

There are two basic ways to set multiple fonts and colors within the text:

  1. Add the text by appending to the Text property and then use SelectionStart and SelectionLength to select the appended text. Then style the selected text. This is similar to the approach used above.
  2. Set the styles and then use the AppendText property.

To try out technique #1, add the following code to the button click event for one of the buttons on the form:

In C#:

// Add another set of text in a different style
string addedText = Environment.NewLine + Environment.NewLine
                     + "This famous quote was from what movie?";
int len = richTextBox1.Text.Length;
richTextBox1.Text += addedText;
richTextBox1.SelectionStart = len;
richTextBox1.SelectionLength = addedText.Length;
richTextBox1.SelectionFont = new Font("Verdana", 10,
                                      FontStyle.Regular);
richTextBox1.SelectionColor = Color.DarkSlateGray;


In VB:

Dim addedText As String = Environment.NewLine & Environment.NewLine & _
                        "This famous quote was from what movie?"
Dim len As Integer = richTextBox1.Text.Length
richTextBox1.Text &= addedText
richTextBox1.SelectionStart = len
richTextBox1.SelectionLength = addedText.Length
richTextBox1.SelectionFont = New Font("Verdana", 10, FontStyle.Regular)
richTextBox1.SelectionColor = Color.DarkSlateGray

This code first stores the length of the current text. This will be the selection start value. The additional text is then appended to the Text property of the RichTextBox. The SelectionStart and SelectionLength are then set as in the prior example. Finally, the font and color are set.

NOTE: You must set the SelectionStart and SelectionLength after you append the text.

To try out technique #2, replace the code in the button click event with this code instead:

In C#:

// Add another set of text in a different style
string addedText = Environment.NewLine + Environment.NewLine
                     + "This famous quote was from what movie?";
richTextBox1.SelectionFont = new Font("Verdana", 10,
                                     FontStyle.Regular);
richTextBox1.SelectionColor = Color.DarkSlateGray;
richTextBox1.AppendText(addedText);

In VB:

' Add another set of text in a different style
Dim addedText As String = Environment.NewLine & Environment.NewLine & _
                        "This famous quote was from what movie?"
richTextBox1.SelectionFont = New Font("Verdana", 10, FontStyle.Regular)
richTextBox1.SelectionColor = Color.DarkSlateGray
richTextBox1.AppendText(addedText)

Notice how much shorter this option is. This technique sets the SelectionFont and SelectionColor and then uses the AppendText method to add the styled text to the RichTextBox.

Regardless of which technique you choose, the result will appear as follows:

image

Highlighting Words

Another common requirement when working with a RichTextBox is to highlight multiple occurrences of a specific word.

To try out this technique, add this code to the other button click event:

In C#:

string wordToFind  = "is";
int startIndex  = 0;

while (startIndex > -1)
{
    startIndex = richTextBox1.Find(wordToFind, startIndex + 1,
                    richTextBox1.Text.Length,
                    RichTextBoxFinds.WholeWord);
    if (startIndex > -1 )
    {
        richTextBox1.Select(startIndex, wordToFind.Length);

        richTextBox1.SelectionFont = new Font("Verdana", 12,
                                FontStyle.Bold | FontStyle.Italic);
        richTextBox1.SelectionColor = Color.Red;
    }
}

In VB:

Dim wordToFind As String = "is"
Dim startIndex As Integer = 0

Do While startIndex > -1
    startIndex = richTextBox1.Find(wordToFind, startIndex + 1, _
                    richTextBox1.Text.Length, _
                    RichTextBoxFinds.WholeWord)
    If startIndex > -1 Then
        richTextBox1.Select(startIndex, wordToFind.Length)

        richTextBox1.SelectionFont = New Font("Verdana", 12, _
                                FontStyle.Bold Or FontStyle.Italic)
        richTextBox1.SelectionColor = Color.Red
    End If
Loop

The code first defines the word to find. If this code is contained in a method instead of an event, the word to find could be passed in as a parameter.

The code then loops through the text in the RichTextBox using the Find method of the RichTextBox to find the next occurrence. The Find method will return –1 when it does not find any matches.

If a match is found, the code uses the Select method to select the found text. It then sets the font and color. This example also demonstrates how to bold AND italicize the text by Or'ing the style flags.

The result appears as follows:

image

Enjoy!

Filed under: , , , ,

Comments

# re: RichTextBox Styles

Sunday, November 01, 2009 6:12 AM by Mark Wisecarver

Thanks a bunch Deborah, this will help a lot of developers.

# re: RichTextBox Styles

Wednesday, November 11, 2009 3:36 PM by Nes

me richtexbox dont working gidme one example

for vb6 U.U please.

# re: RichTextBox Styles

Thursday, November 12, 2009 10:57 AM by Deborah Kurata

If you need help with VB 6, you may want to post your question here:

http://www.vbforums.com/

Hope this helps.

# re: RichTextBox Styles

Monday, November 16, 2009 8:41 AM by Nes

Thanks for your Help.

# re: RichTextBox Styles

Friday, December 11, 2009 8:47 PM by Samirah Khan

i tried the VB code  fro "Highlighting Words" but the trouble is its not searching the Richtextbox from the start i.e the first character in the box.

this is my code:

       Dim startindex As Integer = 0
       Dim wordtofind As String = TextBox1.Text
       Do While startindex > -1
           startindex = RichTextBox1.Find(wordtofind, startindex + 1, RichTextBox1.Text.Length, RichTextBoxFinds.None)
           If startindex > -1 Then
               RichTextBox1.Select(startindex, wordtofind.Length)
               RichTextBox1.SelectionFont = New Font("Verdana", 12, FontStyle.Italic)    
               RichTextBox1.SelectionColor = Color.Red

but it doesnt search from the beginning of the file.

# re: RichTextBox Styles

Sunday, December 13, 2009 1:26 PM by Deborah Kurata

Hi Samirah -

Everything in .NET starts at index 0. You are starting your search at position 1 (startIndex +1), skipping the first character  of the string.

If you require further assistance, please post any questions to here:

social.msdn.microsoft.com/.../categories

Hope this helps.

# re: RichTextBox Styles

Monday, December 21, 2009 11:31 AM by Samirah Khan

thanks much Deboarah for highlighting the error.

its works now

Leave a Comment

(required) 
(required) 
(optional)
(required)