Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
203 views

The RichTextBox Control

The document discusses the RichTextBox control in .NET, which allows for formatted text input and display like bold, italic, underline. It has many properties related to selection, formatting and alignment. Events include selection changed and links clicked. The document provides an example of a basic text editor using a RichTextBox to apply and remove formatting, and load/save content.

Uploaded by

Erwin Acedillo
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views

The RichTextBox Control

The document discusses the RichTextBox control in .NET, which allows for formatted text input and display like bold, italic, underline. It has many properties related to selection, formatting and alignment. Events include selection changed and links clicked. The document provides an example of a basic text editor using a RichTextBox to apply and remove formatting, and load/save content.

Uploaded by

Erwin Acedillo
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

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. Where 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, we used a standard TextBox. We could just as well have used a RichTextBox to do the job. In fact, as we'll see in the example later, you can remove the TextBox name txtOutput 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 textbox is more advanced than the one we explored in the previous section, you'd expect there are new properties that can be used, and you'd be correct. Here are descriptions of the most commonly used properties of the RichTextBox: Name CanRedo Availability Read only Description This property is true if something has been undone, that can be reapplied, otherwise false. This property is true if it is possible to perform an undo action on the RichTextBox, otherwise it is false. This property holds the name of an action that be used to redo something that has been undone in the RichTextBox. Set this property to true to make the control detect URLs and format them (underline as in a browser). This corresponds to the Text property, except that this holds the text in RTF. 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, MS Word, it will retain all formatting. Like SelectedRtf you can use this property to get or set the selected text. Unlike the RTF version of the property however, all formatting is lost. This represents the alignment of the selected text. It can be Center, Left, or Right.

CanUndo

Read only

RedoActionName

Read only

DetectUrls

Read/Write

Rtf SelectedRtf

Read/Write Read/Write

SelectedText

Read/Write

SelectionAlignment

Read/Write

SelectionBullet

Read/Write

BulletIndent SelectionColor SelectionFont SelectionLength SelectionType

Read/Write Read/Write Read/Write Read/Write Read only

ShowSelectionMargin

Read/Write

UndoActionName SelectionProtected

Read only Read/Write

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. Use this property to specify the number of pixels a bullet should be indented. Allow you to change the color of the text in the selection. Allow you to change to font of the text in the selection. Using this property, you either set or retrieve the length of a selection. 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. 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. Gets the name of the action that will be used if the user chooses to undo something. 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 listing above, most of the new properties have to do with a selection. This is 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. There are a few new of interest though: Name LinkedClick Protected SelectionChanged Description This event is sent when a user clicks on a link within the text. This event is sent when a user attempts to modify text that has been marked as protected. 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.

Try it Out RichTextBox Example

We'll create a very basic text editor in this example. It 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. As always, we'll start by designing the form: 1. Create a new C# Windows Application project and name it RichTextBoxTest.

2. Create the form as shown in the picture below. The textbox named txtSize should be a TextBox control. The textbox named rtfText should be a RichTextBox control:

3. Name the controls as indicated in the picture above and clear the Text property of both rtfText and txtSize. 4. Excluding the text boxes, set the Text of all controls to the same as the names except for the first three letters. 5. 6. Change the Text property of the txtSize text box to 10. Anchor the controls as in the following table: Anchor value Bottom Top, Left, Bottom, Right Top

Control name btnLoad and btnSave RtfText All others 7.

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

Adding the Event Handlers That concludes the visual part of the example and we'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 btnBold_Click(object sender, System.EventArgs e) { Font oldFont; Font newFont; // Get the font that is being used in the selected text oldFont = this.rtfText.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.rtfText.SelectionFont = newFont; this.rtfText.Focus(); }

We start by getting the font which is being used in the current selection and assigning it to a local variable. Then we check if this selection is already bold. If it is, we want to remove the bold setting; otherwise we want to set it. We create a new font using the oldFont as the prototype, but add or remove the bold style as needed. Finally, we assign the new font to the selection and return focus to the RichTextBox. See Chapter 16 for a description of the Font object. The event handlers for btnItalic and btnUnderline are the same as the above one, except we are checking the appropriate styles. Double-click the two buttons Italic and Underline and add this code:
private void btnItalic_Click(object sender, System.EventArgs e) { Font oldFont; Font newFont; // Get the font that is being used in the selected text oldFont = this.rtfText.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.rtfText.SelectionFont = newFont; this.rtfText.Focus(); } private void btnUnderline_Click(object sender, System.EventArgs e) { Font oldFont; Font newFont; // Get the font that is being used in the selected text oldFont = this.rtfText.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.rtfText.SelectionFont = newFont; this.rtfText.Focus(); }

Double-click the last of the formatting buttons, Center, and add the following code:
private void btnCenter_Click(object sender, System.EventArgs e) { if (this.rtfText.SelectionAlignment == HorizontalAlignment.Center) this.rtfText.SelectionAlignment = HorizontalAlignment.Left; else this.rtfText.SelectionAlignment = HorizontalAlignment.Center; this.rtfText.Focus(); }

Here we must check another property, SelectionAlignment to see if the text in the selection is already centered. HorizontalAlignment is an enumeration which can be Left, Right, Center, Justify, and NotSet. In this case, we simply check if Center is set, and if it is, we set the alignment to left. If it isn't we set it to Center. The final formatting our little text editor will be able to perform is setting the size of text. We'll add two event handlers for the textbox Size, one for controlling the input, and one to detect when the user has finished enering a value. Add the following lines to the constructor of the form:
public Form1() { InitializeComponent(); // Event Subscription this.txtSize.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSize_KeyPress); this.txtSize.Validating += new

System.ComponentModel.CancelEventHandler(this.txtSize_Validating); }

We saw these two event handlers in the previous example. Both of the events use a helper method called ApplyTextSize, which takes a string with the size of the text:
private void txtSize_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { // Remove all characters that are not numbers, backspace and 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.rtfText.Focus(); } } private void txtSize_Validating(object sender, System.ComponentModel.CancelEventArgs e) { TextBox txt = (TextBox)sender; ApplyTextSize(txt.Text); this.rtfText.Focus(); } private void ApplyTextSize(string textSize) { // Convert the text to a float because we'll be needing a float shortly float newSize = Convert.ToSingle(textSize); FontFamily currentFontFamily; Font newFont; // Create a new font of the same family but with the new size currentFontFamily = this.rtfText.SelectionFont.FontFamily; newFont = new Font(currentFontFamily, newSize); // Set the font of the selected text to the new font this.rtfText.SelectionFont = newFont; }

The work we are interested in takes place in the helper method ApplyTextSize. It starts by converting the size from a string to a float. We've prevented the user from entering anything but integers, but when we create the new font, we need a float, so convert it to the correct type.

After that, we get the family to which the font belongs and we create a new font from that family with the new size. Finally, we set the font of the selection to the new font. That's all the formatting we 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 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. We need to handle the event that is sent when the user clicks a link: LinkClicked. We do this by subscribing to the event as we are now used to doing, in the constructor:
this.rtfText.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.rtfText_LinkedClick);

We 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 rtfText_LinkedClick(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. We'll use a fixed file to do this. Double-click the Load button, and add the following code:
private void btnLoad_Click(object sender, System.EventArgs e) { // Load the file into the RichTextBox try { rtfText.LoadFile("../../Test.rtf"); } catch (System.IO.FileNotFoundException) { MessageBox.Show("No file to load yet"); } }

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

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

Run the example now, format some text, and click Save. Clear the textbox 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 this:

You might also like