The RichTextBox Control


Like the normal TextBox, the RichTextBox control is derived from TextBoxBase. Because of this, it shares a number of features with the TextBox, but is much more diverse. Whereas a TextBox is commonly used with the purpose of obtaining short text strings from the user, the RichTextBox is used to display and enter formatted text (for example bold, underline, and italic). It does so using a standard for formatted text called Rich Text Format, or RTF.

In the previous example, you used a standard TextBox. You could just as well have used a RichTextBox to do the job. In fact, as you see in the example later, you can remove the TextBox name textBoxOutput and insert a RichTextBox in its place with the same name, and the example behaves exactly as it did before.

RichTextBox Properties

If this kind of text box is more advanced than the one you explored in the previous section, you'd expect there are new properties that can be used, and you'd be correct. The following table describes the most commonly used properties of the RichTextBox:

Name

Description

CanRedo

This property is true when the last undone operation can be reap- plied using Redo.

CanUndo

This property is true if it is possible to undo the last action on the RichTextBox. Note that CanUndo is defined in TextBoxBase, so it is available to TextBox controls as well.

RedoActionName

This property holds the name of an action that would be performed by the Redo method.

DetectUrls

Set this property to true to make the control detect URLs and format them (underline as in a browser).

Rtf

This corresponds to the Text property, except that this holds the text in RTF.

SelectedRtf

Use this property to get or set the selected text in the control, in RTF. If you copy this text to another application, for example, Word, it will retain all formatting.

SelectedText

As with SelectedRtf, you can use this property to get or set the selected text. However, unlike the RTF version of the property, all formatting is lost.

SelectionAlignment

This represents the alignment of the selected text. It can be Center, Left, or Right.

SelectionBullet

Use this property to find out if the selection is formatted with a bullet in front of it, or use it to insert or remove bullets.

BulletIndent

Use this property to specify the number of pixels a bullet should be indented.

SelectionColor

This property allows you to change the color of the text in the selection.

SelectionFont

This property allows you to change the font of the text in the selection.

SelectionLength

Using this property, you either set or retrieve the length of a selection.

SelectionType

This property holds information about the selection. It will tell you if one or more OLE objects are selected or if only text is selected.

ShowSelectionMargin

If you set this property to true, a margin will be shown at the left of the RichTextBox. This will make it easier for the user to select text.

UndoActionName

Gets the name of the action that will be used if the user chooses to undo something.

SelectionProtected

You can specify that certain parts of the text should not be changed by setting this property to true.

As you can see from the preceding listing, most of the new properties have to do with a selection. This is so because any formatting you will be applying when a user is working on his or her text will probably be done on a selection made by that user. In case no selection is made, the formatting will start from the point in the text where the cursor is located, called the insertion point.

RichTextBox Events

Most of the events used by the RichTextBox are the same as those used by the TextBox. The following table presents a few new ones of interest, though.

Name

Description

LinkClicked

This event is sent when a user clicks on a link within the text.

Protected

This event is sent when a user attempts to modify text that has been marked as protected.

SelectionChanged

This event is sent when the selection changes. If for some reason you don't want the user to change the selection, you can prevent the change here.

In the next Try It Out, you create a very basic text editor. The example demonstrates how to change basic formatting of text and how to load and save the text from the RichTextBox. For the sake of simplicity, the example loads from and saves to a fixed file.

Try It Out – RichTextBox Example

image from book

As always, you start by designing the form:

  1. Create a new C# Windows application called RichTextBoxTest in the C:\BegVCSharp\ Chapter14 directory.

  2. Create the form as shown in Figure 14-14. The text box named txtSize should be a TextBox control. The text box named RichTextBoxText should be a RichTextBox control.

    image from book
    Figure 14-14

  3. Name the controls as indicated in the picture.

  4. Apart from the text boxes, set the Text of all controls to the same as the names except for the first part of the name that describes the type of the control.

  5. Change the Text property of the textBoxSize text box to 10.

  6. Anchor the controls as in the following table.

    Control name

    Anchor value

    buttonLoad and buttonSave

    Bottom

    richTextBoxText

    Top, Left, Bottom, Right

    All others

    Top

  7. Set the MinimumSize property of the form to the same as the Size property.

How It Works

That concludes the visual part of the example, and you'll move straight to the code. Double-click the Bold button to add the Click event handler to the code. Here is the code for the event:

private void buttonBold_Click(object sender, EventArgs e) { Font oldFont; Font newFont; // Get the font that is being used in the selected text oldFont = this.richTextBoxText.SelectionFont; // If the font is using bold style now, we should remove the // Formatting. if (oldFont.Bold) newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Bold); else newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold); // Insert the new font and return focus to the RichTextBox. this.richTextBoxText.SelectionFont = newFont; this.richTextBoxText.Focus(); }

You start by getting the font that is being used in the current selection and assigning it to a local variable oldFont. Then you check if this selection is already bold. If it is, you want to remove the bold setting; otherwise, you want to set it. You create a new font using oldFont as the prototype but add or remove the bold style as needed.

Finally, you assign the new font to the selection and return focus to the RichTextBox — you look at the Font object more in Chapter 30.

The event handlers for buttonItalic and buttonUnderline are the same as the one above, except that you are checking the appropriate styles. Double-click the two buttons Italic and Underline and add this code:

private void buttonUnderline_Click(object sender, EventArgs e) { Font oldFont; Font newFont; // Get the font that is being used in the selected text. oldFont = this.richTextBoxText.SelectionFont; // If the font is using Underline style now, we should remove it. if (oldFont.Underline) newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Underline); else newFont = new Font(oldFont, oldFont.Style | FontStyle.Underline); // Insert the new font. this.richTextBoxText.SelectionFont = newFont; this.richTextBoxText.Focus(); }     private void buttonItalic_Click(object sender, EventArgs e) { Font oldFont; Font newFont; // Get the font that is being used in the selected text. oldFont = this.richTextBoxText.SelectionFont; // If the font is using Italic style now, we should remove it. if (oldFont.Italic) newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Italic); else newFont = new Font(oldFont, oldFont.Style | FontStyle.Italic); // Insert the new font. this.richTextBoxText.SelectionFont = newFont; this.richTextBoxText.Focus(); }

Double-click the last of the formatting buttons, Center, and add the following code:

 private void buttonCenter_Click(object sender, EventArgs e) { if (this.richTextBoxText.SelectionAlignment == HorizontalAlignment.Center) this.richTextBoxText.SelectionAlignment = HorizontalAlignment.Left; else this.richTextBoxText.SelectionAlignment = HorizontalAlignment.Center; this.richTextBoxText.Focus(); } 

Here, you must check another property, SelectionAlignment, to see if the text in the selection is already centered. You do this because you want the button to behave like a toggle button — if the text is centered it becomes left-justified, otherwise it becomes centered. HorizontalAlignment is an enumeration with values Left, Right, Center, Justify, and NotSet. In this case, you simply check if Center is set, and if it is, you set the alignment to left. If it isn't you set it to Center.

The final formatting your little text editor will be able to perform is setting the size of text. You'll add two event handlers for the text box Size, one for controlling the input, and one to detect when the user has finished entering a value.

Find and double-click the KeyPress and Validating events for the textBoxSize control in the Properties panel to add the handlers to the code.

You saw these two event handlers in the previous example. Both of the events use a helper method called ApplyTextSize that takes a string with the size of the text.

private void textBoxSize_KeyPress(object sender, KeyPressEventArgs e) { // Remove all characters that are not numbers, backspace, or enter. if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13) { e.Handled = true; } else if (e.KeyChar == 13) { // Apply size if the user hits enter TextBox txt = (TextBox)sender; if (txt.Text.Length > 0) ApplyTextSize(txt.Text); e.Handled = true; this.richTextBoxText.Focus(); } }     private void textBoxSize_Validating(object sender, CancelEventArgs e) { TextBox txt = (TextBox)sender; ApplyTextSize(txt.Text); this.richTextBoxText.Focus(); }     private void ApplyTextSize(string textSize) { // Convert the text to a float because we'll float newSize = Convert.ToSingle(textSize); FontFamily currentFontFamily; Font newFont; // Create a new font of the same family but with the new size. currentFontFamily = this.richTextBoxText.SelectionFont.FontFamily; newFont = new Font(currentFontFamily, newSize); // Set the font of the selected text to the new font. this.richTextBoxText.SelectionFont = newFont; } 

The work you are interested in takes place in the helper method ApplyTextSize(). It starts by converting the size from a string to a float. You prevented users from entering anything but integers, but when you create the new font, you need a float, so convert it to the correct type.

After that, you get the family to which the font belongs and create a new font from that family with the new size. Finally, you set the font of the selection to the new font.

That's all the formatting you can do, but some is handled by the RichTextBox itself. If you try to run the example now, you will be able to set the text to bold, italic, and underline, and you can center the text. That is what you expect, but there is something else that is interesting — try to type a Web address, for example http://www.wrox.com in the text. The text is recognized by the control as an Internet address, is underlined, and the mouse pointer changes to a hand when you move it over the text. If that leads you to believe that you can click it and be brought to the page, you are almost correct. You need to handle the event that is sent when the user clicks a link: LinkClicked.

Find the LinkClicked event in the Properties panel and double-click it to add an event handler to the code. You haven't seen this event handler before — it is used to provide the text of the link that was clicked. The handler is surprisingly simple and looks like this:

private void richTextBoxText_LinkClicked (object sender,                                     System.Windows.Forms.LinkClickedEventArgs e) { System.Diagnostics.Process.Start(e.LinkText); }

This code opens the default browser if it isn't open already and navigates to the site to which the link that was clicked is pointing.

The editing part of the application is now done. All that remains is to load and save the contents of the control. You use a fixed file to do this.

Double-click the Load button, and add the following code:

private void buttonLoad_Click(object sender, EventArgs e) { // Load the file into the RichTextBox. try { richTextBoxText.LoadFile("Test.rtf"); } catch (System.IO.FileNotFoundException) { MessageBox.Show("No file to load yet"); } } 

That's it! Nothing else has to be done. Because you are dealing with files, there is always a chance that you might encounter exceptions, and you have to handle these. In the Load method, you handle the exception that is thrown if the file doesn't exist. It is equally simple to save the file. Double-click the Save button and add this:

private void buttonSave_Click(object sender, EventArgs e) { // Save the text. try { richTextBoxText.SaveFile("Test.rtf"); } catch (System.Exception err) { MessageBox.Show(err.Message); } }

Run the example now, format some text and click Save. Clear the text box and click Load, and the text you just saved should reappear.

This concludes the RichTextBox example. When you run it, you should be able to produce something like Figure 14-15.

image from book
Figure 14-15

image from book




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net