Creating a Rich Text Control
|
|
To support a rich text, the .NET Framework provides the
RichTextBox control that is implement from the RichTextBox class. Like
TextBox, the RichTextBox class is based on TextBoxBase.
Therefore, to have right text in an application, from the Common Controls
section of the Toolbox, click RichTextBox and click the form.
To programmatically create rich text, declare a variable of
type RichTextBox, use the new operator to allocate memory for it, and add it to
the Controls collection of its parent. Here is an example:
Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Public Class Starter
Inherits Form
Private rchNote As RichTextBox
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
rchNote = New RichTextBox()
Controls.Add(rchNote)
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
Practical Learning: Starting a Rich Text Application
|
|
- Start Microsoft Visual Basic and create a new Windows Application named
Notice1
- In the Solution Explorer, right-click Form1.cs and click Rename
- Type Editor.vb as the new name of the form and press Enter
- From the Dialogs section of the Toolbox, click OpenFileDialog
and click the form
- In the Properties window, click DefaultExt and type rtf
- Click (Name) and type dlgOpen
- Click Filter and type Rich Text Format (*.rtf)|*.rtf|Text File
(*.txt)|*.txt|All Files|
- From the Dialogs section of the Toolbox, click SaveFileDialog
and
click the form
- In the Properties window, click DefaultExt and type rtf
- Click (Name) and type dlgSave
- Click Filter and type Rich Text Format (*.rtf)|*.rtf|Text File
(*.txt)|*.txt|All Files|
- From the Common Controls section of the Toolbox, click RichTextBox
and click the form
- From the Menus & Toolbars section of the Toolbox, click MenuStrip and
click the form
- On the form, click Type Here, type File and press Enter
- Under File, click Type Here, type New and press Enter
- On the right side of File, click Type Here, type Edit and press
Enter
- Under Edit, click Type Here, type New and press Enter
- In the same way, complete the menu strip with the following items:
- On the form and click the rich text control
- In the Properties window, change the its properties as follows:
Name: rchEditor
AcceptsTab: True
Font: Times New Roman, 12pt
Dock: Fill
ScrollBars: Vertical
- Right-click the form and click View Code
- In the Class Name combo box, select (Editor Events)
- In the Method Name combo box, select Load and change the file as
follows:
Imports System.IO
Public Class Editor
Private CurrentFileName As String
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles Me.Load
CurrentFileName = "<Not Allowed>"
rchEditor.Modified = False
End Sub
End Class
|
- In the Class Name combo box, select mnuEdit Undo
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuEditUndo_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuEditUndo.Click
rchEditor.Undo()
End Sub
|
- In the Class Name combo box, select mnuEditRedo
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuEditRedo_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuEditUndo.Click
rchEditor.Redo()
End Sub
|
- In the Class Name combo box, select mnu Edit Cut
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuEditCut_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuEditCut.Click
rchEditor.Cut()
End Sub
|
- In the Class Name combo box, select mnu Edit Copy
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuEditCopy_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuEditCopy.Click
rchEditor.Copy()
End Sub
|
- In the Class Name combo box, select mnu Edit Paste
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuEditPaste_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuEditPaste.Click
rchEditor.Paste()
End Sub
|
- In the Class Name combo box, select mnuEdit Select All
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuSelectAll_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuSelectAll.Click
rchEditor.SelectAll()
End Sub
|
- In the Class Name combo box, select mnu Format Word Wrap
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFormatWordWrap_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFormatWordWrap.Click
rchEditor.WordWrap = True
End Sub
|
- Save all
The Text of a Rich Text Box
|
|
Like the other graphical Windows controls, the right text
box uses the common characteristics such as the location, the size, the minimum
size, the maximum size, the anchor, the docking, the font, the ability to be
visible or hidden, the ability to be enabled or disabled, and the border style.
Like the TextBox control, the rich text control inherits various characteristics
from the TextBoxBase class, including the Text property, the
Lines collection, the read-only attribute, the ability to select and
manipulate text. The rich text box also shares various characteristics with the
multi-line text box such as the Multiline property, the scroll bars, the
word wrap, the ability to accept the Tab and the Enter keys. Here is an example:
Public Sub InitializeComponent()
rchNote = New RichTextBox()
rchNote.Size = New Size(Width, Height)
rchNote.Multiline = True
rchNote.ScrollBars = RichTextBoxScrollBars.Both
rchNote.AcceptsTab = True
rchNote.Font = New Font("Verdana", 10.0F)
Dim strLines As String() = _
{ _
"LeavingSydney", _
"When we decided to leave, we knew we were " & _
"making a hard decision. We had spent so much " & _
"time this had become our new home. A few " & _
"weeks or months before, we wanted to make " & _
"Sydney our newly found settlement, a " & _
"permanent place we could proudly call ours. " & _
"It appeared that, unpredictably, fate had " & _
"decided otherwise.", _
"Author: Arthur D. Pale", _
"Title: Stories Of My Life" _
}
rchNote.Lines = strLines
Controls.Add(rchNote)
Controls.Add(rchNote)
End Sub
Saving the Contents of a Rich Text Document
|
|
After creating and formatting a rich text document, you may
want to save it for later use. To support this, the RichTextBox class
provides a method named named SaveFile that is overloaded with three
versions. One of the versions uses the following syntax:
Public Sub SaveFile(path As String)
This method takes as argument the name or path to a file. It
will save the file as RTF. If you want the user to save a file that is either
RTF, ASCII, or another format, to specify the desired format, you can use the
following version of the method:
Public Sub SaveFile(data As Stream, fileType As RichTextBoxStreamType)
As seen in the first version, the first argument is the name
or path of the file. The second argument allows you to specify the type of file
that is being saved, which could be a normal ASCII text. This argument is of
type RichTextBoxStreamType, which is an enumeration. The members of the
RichTextBoxStreamType enumeration are PlainText, RichNoOleObjs,
RichText, TextTextOleObjs, or TextTextOleObjs.
Instead of directly using the name of the file, you can
create it as a stream. In this case, the RichTextBox class provides the
following version of the SaveFile() method:
Public Sub SaveFile(path As String, fileType As RichTextBoxStreamType)
This version expects a Stream-based object such as a
FileStream variable.
To assist you with opening a rich text file, the
RichTextBox class is equipped with the LoadFile() method overloaded
with three versions. The simplest versions has the following syntax:
Public Sub LoadFile(path As String)
This method takes as argument the name or path to a file.
The file must be in RTF format. If it is not, the file will not be opened and
the compiler would throw an IOException exception. If you want to give
the user the ability to open different types of files, you should use the
following version of the LoadFile() method:
Public Sub LoadFile(data As Stream, fileType As RichTextBoxStreamType)
The first argument is the same as a the single argument of
the first version. The second argument allows you to specify the type of file
that is being opened, which could be a normal ASCII text. This argument is of
type RichTextBoxStreamType.
Instead of directly using the name of the file, you can
create it as a stream. In this case, the RichTextBox class provides the
following version of the LoadFile() method:
Public Sub LoadFile(path As String, fileType As RichTextBoxStreamType)
This version expects a Stream-based object such as a
FileStream variable.
Practical
Learning: Opening a Rich Text File
|
|
- In the Class Name combo box, click mnu File New
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFileNew_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFileNew.Click
' This is the question the user will have to answer
Dim answer As MsgBoxResult = MsgBox( _
"The document has changed. Do you want to save it?" & _
vbCrLf & "Click\n" & _
"Yes:\tTo save the document and create a new one.\n" & _
"No:\tNot to save the document but create a new one.\n" & _
"Cancel:\tNot to do anything", _
MsgBoxStyle.YesNo Or MsgBoxStyle.Question, _
"Editor - Saving a File")
' When the user clicks File -> New to start a new document,
' before creating a new document,
' find out if the document is "dirty"
' sk the user whether to save or not
If rchEditor.Modified = True Then
' Present the message box to the user who
' will decide whether to save
If answer = MsgBoxResult.Yes Then
' If the user answers Yes
' Find out if the current document has never been saved
If CurrentFileName = "<Not Allowed>" Then
' If it has never been saved,
' then display the Save dialog box
If dlgSave.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Save the file
rchEditor.SaveFile(dlgSave.FileName)
' Change the current file name to something not allowed
CurrentFileName = "<Not Allowed>"
' Display Untitled name of the
' current file on the title bar
Text = "Parasol - Untitled"
' Since the document has been saved and the user wants
' to create a new one, empty the control
rchEditor.Clear()
' Update the Modified attribute
rchEditor.Modified = False
Else ' the user had clicked Cancel, don't do anything
Exit Sub
End If
Else ' If the document was saved before, then simply update it
rchEditor.SaveFile(CurrentFileName)
' Change the current file name to something not allowed
CurrentFileName = "<Not Allowed>"
' Display Untitled name of the current file on the title bar
Text = "Parasol - Untitled"
rchEditor.Clear()
' Update the Modified attribute
rchEditor.Modified = False
End If
ElseIf answer = MsgBoxResult.No Then
' If the user answered No,
' then simply start a new document
rchEditor.Clear()
' Change the current file name to something not allowed
CurrentFileName = "<Not Allowed>"
' Display Untitled name of the current file on the title bar
Text = "Parasol - Untitled"
' Update the Modified attribute
rchEditor.Modified = False
Else ' If the user clicked Cancel, don't do anything
Exit Sub
End If
Else ' If the document was not modified, then start a new one
' If the user answered No,
' then simply start a new document
rchEditor.Clear()
' Change the current file name to something not allowed
CurrentFileName = "<Not Allowed>"
' Display Untitled name of the current file on the title bar
Text = "Parasol - Untitled"
' Update the Modified attribute
rchEditor.Modified = False
End If
End Sub
|
- In the Class Name combo box, click mnuFileOpen
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFileOpen_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFileOpen.Click
' Find out if there was a document and if the document was "dirty"
If rchEditor.Modified = True Then
' Here is the question the user will answer
Dim answer As MsgBoxResult = MsgBox( _
"The document has changed. Do you want to save it?" & _
vbCrLf & "Click\n" & _
"Yes:\tTo save the document and open a new one.\n" & _
"No:\tNot to save the document but open a new one.\n" & _
"Cancel:\tNot to do anything", _
MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question, _
"Editor - Opening a File")
' Find out if the user wants to save the current document
If answer = MsgBoxResult.Yes Then
' Find out if this is a new document
If CurrentFileName = "<Not Allowed>" Then
' Since the user wants to save the
' document, display the Save dialog box
If dlgSave.ShowDialog() = _
Windows.Forms.DialogResult.OK Then
' Save the file
rchEditor.SaveFile(dlgSave.FileName)
Else
Exit Sub
End If
else
' This was not a new document,
' so, simply save it
rchEditor.SaveFile(CurrentFileName)
End If
ElseIf answer = MsgBoxResult.No Then
' If the user answered No to the question, don't save
' Simply open the file
If dlgOpen.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Open the new document after letting the user select it
rchEditor.LoadFile(dlgOpen.FileName)
' Change the file name of our archives
CurrentFileName = dlgOpen.FileName
' Get the name of the file that the user selected
Dim fleParasol As FileInfo = _
New FileInfo(dlgOpen.FileName)
Text = "Parasol - " & fleParasol.Name
rchEditor.Modified = False
Else
Exit Sub
End If
else
Exit Sub
End If
else
If dlgOpen.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Open the new document after letting the user select it
rchEditor.LoadFile(dlgOpen.FileName)
' Change the file name of our archives
CurrentFileName = dlgOpen.FileName
' Get the name of the file that the user selected
Dim fleParasol As FileInfo = New FileInfo(dlgOpen.FileName)
Text = "Parasol - " & fleParasol.Name
rchEditor.Modified = False
End If
End If
End Sub
|
- In the Class Name combo box, click mnuFileSave
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFileSave_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFileSave.Click
' Find out if the current document has never been saved
' but is not empty
If (rchEditor.Modified = True) And _
(CurrentFileName = "<Not Allowed>") Then
' Since the document is dirty, display the Save As dialog box
If dlgSave.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Retrieve the new name file and display
' the file in the rich edit control
rchEditor.SaveFile(dlgSave.FileName)
' Change/Update the global and complete name of the file,
' including its path
CurrentFileName = dlgSave.FileName
' Extract the name of the file
Dim fleParasol As FileInfo = New FileInfo(dlgSave.FileName)
' Display the name of the current file on the title bar
Text = "Parasol - " & fleParasol.Name
Else
Exit Sub
End If
Else
' It appears that this document already had a name
' but the document was previously modified
' Therefore, simply save it internally
rchEditor.SaveFile(CurrentFileName)
End If
End Sub
|
- In the Class Name combo box, click mnuFileSave As
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFileSaveAs_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFileSaveAs.Click
If dlgSave.ShowDialog() = Windows.Forms.DialogResult.OK Then
rchEditor.SaveFile(dlgSave.FileName)
' Change the file name of our archives
CurrentFileName = dlgSave.FileName
' Get the name of the file that the user selected
Dim fleParasol As FileInfo = New FileInfo(dlgSave.FileName)
Text = "Parasol - " & fleParasol.Name
rchEditor.Modified = False
End If
End Sub
|
- In the Class Name combo box, click mnuFile Exit
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFileExit_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFileExit.Click
' Is the document dirty?
If rchEditor.Modified = True Then
' Since the document is dirty, find out
' if the user wants to save it
Dim Answer As MsgBoxResult = MsgBox( _
"The document has changed. Do you want to save it?" & _
vbCrLf & "Click\n" & _
"Yes:\tTo save the document and close the application.\n" & _
"No:\tNot to save the document but close the application.\n" & _
"Cancel:\tNot to do anything", _
MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question, _
"Parasol - Saving a File")
' If the user wants to save it
If Answer = MsgBoxResult.Yes Then
' Behave as if the user had clicked File . Save
mnuFileSave_Click(sender, e)
Close()
ElseIf Answer = MsgBoxResult.No Then
' If the user doesn't want to save the document
Close()
' The user cancelled the action: do nothing
Else
Exit Sub
End If
Else ' There is no action to take
Close()
End If
End Sub
|
- Return to the form
We saw that you could change the general font of a text box
and you can change the color of the characters. If you do this on a text box,
all of the characters are changed to the same font and the same color. One of
the extended properties of a rich text box over a regular text box is the
ability to change the font and/ the color of individual characters, words, or
paragraphs and the change applies only to the desired characters.
Before changing a character or a word, you must first select
it. To change the font of the text that is selected on the control, the selected
text is identified with the SelectionFont property. To change the color
of the text that is selected, the selected text is identified with the
SelectionColor property.
To assist you with this, you can use the Font dialog box.
After selecting the character or word, you can transfer their attributes to the
Font dialog box before displaying it. After using the dialog box, if the user
clicks OK, you can retrieve the font and color characteristics then apply them
to the selected character or text.
Practical Learning: Formatting Text
|
|
- From the Dialogs section of the Toolbox, click FontDialog
and click the form
- Click (Name) and type dlgFont
- Double-click ShowColor to set its value to True
- Right-click the form and click View Code
- In the Class Name combo box, select mnu Format Font
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFormatFont_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFormatFont.Click
' Get the characteristics of the selected text
' Apply them to the Font dialog box
dlgFont.Font = rchEditor.SelectionFont
dlgFont.Color = rchEditor.SelectionColor
If dlgFont.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Display the Font dialog box
' If the user clicks OK, get the characteristics of the font
' Apply them to the selected text of the Rich Edit control
rchEditor.SelectionFont = dlgFont.Font
rchEditor.SelectionColor = dlgFont.Color
End If
End Sub
|
- Save all
For a text-based control, a paragraph is a series of words
that start with a letter or empty space until the flow of text is interrupted,
which is usually made with a carriage return, or the end of the document. By
itself, the paragraph controls its alignment and such details as Tab
measurements or indentation. To set or change the properties of a paragraph, you
must first select it. To select a paragraph, you don't need to formally select
it or any portion of its text. As long as the cursor is positioned inside of the
paragraph, any paragraph attribute you set or change would apply to the whole
paragraph. To manipulate more than one paragraph at the same time, you or your
user must select them. The paragraphs do not need to be wholly selected. As long
as a section is selected on it, a paragraph is considered selected.
The most common property of a
paragraph is its alignment, which states whether the paragraph is positioned to
the left, the center, or the right. This characteristic is controlled by the
SelectionAlignment property. The SelectionAlignment property is based
on the HorizontalAlignment enumeration whose members are Left,
Center, and Right. Because this property is applied on (individual)
paragraphs, it is not available at design time.
To change the alignment at run time, assign the desired
value to the SelectionAlignment property.
Practical Learning: Aligning a Paragraph
|
|
- In the Class Name combo box, click mnuFormat Align Left
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFormatAlignLeft_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFormatAlignLeft.Click
rchEditor.SelectionAlignment = HorizontalAlignment.Left
End Sub
|
- In the Class Name combo box, click mnuFormat Align Center
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFormatAlignCenter_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFormatAlignCenter.Click
rchEditor.SelectionAlignment = HorizontalAlignment.Center
End Sub
|
- In the Class Name combo box, click mnuFormat Align Right
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFormatAlignRight_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFormatAlignRight.Click
rchEditor.SelectionAlignment = HorizontalAlignment.Right
End Sub
|
- Return to the form
The Indentation of a Paragraph
|
|
Indentation is the number of empty
characters that separate a paragraph edge from one of the borders of the rich
text control. Indentation refers to the left side or the right side of a
paragraph. Based on this, left indentation refers to the number of empty
characters from the left border of the rich text control to the left edge of a
paragraph. The rich text control provides indentation through various
properties.
To support indentation from the left side of a paragraph,
the RichTextBox class is equipped with a property named
SelectionIndent property. To indent from the right side, the RichTextBox is
equipped with the SelectionRightIndent property.
Practical Learning: Indenting a Paragraph
|
|
- In the Class Name combo box, click mnuFormat Left Indent
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFormatLeftIndent_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFormatLeftIndent.Click
rchEditor.SelectionIndent += 10
End Sub
|
- In the Class Name combo box, click mnuFormat Right Indent
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub mnuFormatRightIndent_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFormatRightIndent.Click
rchEditor.SelectionRightIndent += 10
End Sub
|
- Return to the form
Instead of just a regular section made only of text, you can
create an unordered list of lines or paragraphs in your document. To support
this, the RichTextBox class is equipped with a Boolean property named
SelectionBullet. If you set this property to false on a paragraph, the
paragraph would start with a bullet. If you apply this property to more than one
consecutive paragraph, each would start with a bullet.
Practical Learning: Using a Rich Text Control
|
|
- In the Class Name combo box, click mnu FormatBulletList
- In the Method Name combo box, select Click and implement their Click
events as follows:
Private Sub mnuFormatBulletList_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles mnuFormatBulletList.Click
rchEditor.SelectionBullet = True
End Sub
|
- Execute the application and test the editor
- Close the form and return to your programming environment
|
|