Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

THE RICHTEXTBOX CONTROL 305

These properties determine which of the options on the dialog box will be available to the user. To retrieve the properties of the printout specified by the user on the dialog box, you must use the PrinterSettings object. This object exposes many properties, such as FromPage and ToPage (which determine the starting and ending page of the printout), Copies (which determines the number of copies of the printout), and PrinterName (the name of the selected printer). The PrinterSettings property is discussed in detail in Chapter 15.

The following statements create a new PrinterSettings object, pass it to the Print dialog box, and then display the dialog box. Upon return, they print a few of the settings specified by the user on the Print dialog box. Place an instance of the PrintDialog control to the form and enter the following statements in a button’s Click event handler to test them:

PrintDialog1.AllowSomePages = True

PrintDialog1.AllowSelection = True

PrintDialog1.PrinterSettings = _

New System.Drawing.Printing.PrinterSettings()

PrintDialog1.ShowDialog()

Console.WriteLine(“FROM PAGE: “ & PrintDialog1.PrinterSettings.FromPage)

Console.WriteLine(“TO PAGE: “ & PrintDialog1.PrinterSettings.ToPage)

Console.WriteLine(“# OF COPIES: “ & PrintDialog1.PrinterSettings.Copies)

Console.WriteLine(“PRINTER NAME:” & PrintDialog1.PrinterSettings.PrinterName)

Console.WriteLine(“PRINT RANGE: “ & PrintDialog1.PrinterSettings.PrintRange)

Console.WriteLine(“LANDSCAPE: “ & PrintDialog1.PrinterSettings.LandscapeAngle)

The output produced by the previous statements on my system looked like this:

FROM PAGE:

3

TO PAGE:

4

# OF COPIES:

1

PRINTER NAME:Epson Stylus Photo 750 ESC/P 2

PRINT RANGE:

2

LANDSCAPE:

270

To set the orientation of the printout, you must click the Properties button on the Print dialog box. This action will display the property pages dialog box of the specified printer, where you can set properties like the page’s orientation, the quality of the printout, and other printer-dependent properties. The value 270 returned by the LandscapeAngle indicates the angle of rotation for the printout. The default orientation is Portrait, and the document must be rotated by 270 degrees clockwise for the Landscape orientation.

The PrinterSettings object, as well as the related PageSettings object, are explored in detail in Chapter 15, where you’ll learn how to print documents with the .NET Framework and Visual Basic.

The RichTextBox Control

The RichTextBox control is the core of a full-blown word processor. It provides all the functionality of a TextBox control; in addition, it gives you the capability to mix different fonts, sizes, and attributes; and it gives you precise control over the margins of the text (see Figure 7.9). You can even place images in your text on a RichTextBox control (although you won’t have the kind of control over the embedded images that you have with Microsoft Word).

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

306 Chapter 7 MORE WINDOWS CONTROLS

Figure 7.9

A word processor based on the functionality of the RichTextBox control

The fundamental property of the RichTextBox control is its RTF property. Similar to the Text property of the TextBox control, this property is the text displayed on the control. Unlike the Text property, which returns (or sets) the text of the control but doesn’t contain formatting information, the RTF property returns the text along with any formatting information. Therefore, you can use the RichTextBox control to specify the text’s formatting, including paragraph indentation, font, and font size or style.

RTF stands for Rich Text Format, which is a standard for storing formatting information along with the text. The beauty of the RichTextBox control for programmers is that they don’t need to supply the formatting codes. The control provides simple properties that turn the selected text into bold, change the alignment of the current paragraph, and so on. The RTF code is generated internally by the control and used to save and load formatted files. It’s possible to create elaborately formatted documents without knowing the RTF language.

Note The WordPad application that comes with Windows is based on the RichTextBox control. You can easily duplicate every bit of WordPad’s functionality with the RichTextBox control, as you will see later on in the section “VB.NET at Work: The RTFPad Project.”

The RTF Language

A basic knowledge of the RTF format, its commands, and how it works, will certainly help you understand how the RichTextBox control works. RTF is a language that uses simple commands to specify the formatting of a document. These commands, or tags, are ASCII strings, such as \par (the tag that marks the beginning of a new paragraph) and \b (the tag that turns on the bold style). And this is where the value of the RTF format lies. RTF documents don’t contain special characters and can be easily exchanged among different operating systems and computers, as long as there is an RTF-capable application to read the document. Let’s look at the RTF document in action.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE RICHTEXTBOX CONTROL 307

Open the WordPad application (choose Start Programs Accessories WordPad) and enter a few lines of text (see Figure 7.10). Select a few words or sentences and format them in different ways with any of WordPad’s formatting commands. Then save the document in RTF format: Choose File Save As, select Rich Text Format, and then save the file as Document.rtf. If you open this file with a text editor such as Notepad, you’ll see the actual RTF code that produced the document. You can find the RTF file for the document shown in Figure 7.10 in this chapter’s folder on the CD; a small section of the RTF document is presented in Listing 7.3.

Figure 7.10

The formatting applied to the text using WordPad’s commands is stored along with the text in RTF format.

Listing 7.3: Excerpt from the RTF Code for the Document of Figure 7.9

{\rtf1\ansi\ansicpg1252\deff0\deflang1033 {\fonttbl{\f0\fnil\fcharset0 Verdana;}{\f1\fswiss\fcharset0 Arial;}}

\viewkind4\uc1\pard\nowidctlpar\fi720\b\f0\fs18 RTF \b0 stands for \i Rich Text Format\i0 , which is a standard for storing formatting information along with the text. The beauty of the RichTextBox control for programmers is that they don\rquote t need to supply the formatting codes. The control provides simple properties that turn the selected text into bold, change the alignment of the current paragraph, and so on.\par

As you can see, all formatting tags are prefixed with the backslash (\) symbol. To display the \ symbol itself, insert an additional slash. Paragraphs are marked with the \par tag, and the entire document is enclosed in a pair of curly brackets. The \li and \ri tags followed by a numeric value specify the amount of the left and right indentation. If you assign this string to the RTF property of a RichTextBox control, the result will be the document shown in Figure 7.10, formatted exactly as it appears in WordPad.

RTF is similar to HTML (Hypertext Markup Language), and if you’re familiar with HTML, a few comparisons between the two standards will provide helpful hints and insight into the RTF language. Like HTML, RTF was designed to create formatted documents that could be displayed on different systems. The RTF language uses tags to describe the document’s format. For example, the

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

308 Chapter 7 MORE WINDOWS CONTROLS

tag for italics is \i, and its scope is delimited with a pair of curly brackets. The following RTF segment displays a sentence with a few words in italics:

{{\b RTF} (which stands for Rich Text Format) is a {\i document formatting language} that uses simple commands to specify the formatting of the document.}

The following is the equivalent HTML code:

<b>RTF</b> (which stands for Rich Text Format) is a <i>document formatting language</i> that uses simple commands to specify the formatting of the document.

The <b> and <i> tags of HTML are equivalent to the \b and \i tags of RTF. RTF, however, is much more complicated than HTML. It’s not nearly as easy to understand an RTF document as it is to understand an HTML document because RTF was meant to be used internally by applications. As you can see in Listing 7.3, RTF contains information about the font being used, its size, and so on. Just as you need a browser to view HTML documents, you need an RTF-capable application to view RTF documents. WordPad, for instance, supports RTF and can both save a document in RTF format and read RTF files.

You’re not expected to supply your own RTF code to produce a document. You simply select the segment of the document you want to format and apply the corresponding formatting command from within your word processor. Fortunately, the RichTextBox control isn’t any different. It doesn’t require you or the users of your application to understand RTF code. The RichTextBox control does all the work for you while hiding the low-level details.

VB.NET at Work: The RTFDemo Project

The RTFDemo project, shown in Figure 7.11, demonstrates the principles of programming the RichTextBox control. The RichTextBox control is the large box covering the upper section of the form where you can type text as you would with a regular TextBox control.

Figure 7.11

The RTFDemo project demonstrates how the RichTextBox control handles RTF code.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE RICHTEXTBOX CONTROL 309

Use the first three buttons to set styles for the selected text. The Bold and Italic buttons are selfexplanatory; the Regular button restores the regular style of the text. All three buttons create a new font based on the current font of the RichTextBox control and turn on the appropriate attribute.

Here’s the code behind the Bold button:

Private Sub bttnBold_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles bttnBold.Click

Dim fnt As New Font(RichTextBox1.Font, FontStyle.Bold)

RichTextBox1.SelectionFont = fnt

End Sub

The code for the Italic button is quite similar, it simply sets a different attribute:

Private Sub bttnItalic_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles bttnItalic.Click

Dim fnt As New Font(RichTextBox1.Font, FontStyle.Italic)

RichTextBox1.SelectionFont = fnt

End Sub

Both buttons create a new Font object based on the current font of the control. The second argument of the Font’s constructor is a constant with the font’s attributes. The code shown here turns on the Bold and Italic attributes of the font. The second statement in the two handlers assigns the new font to the selected text (property SelectionFont). Notice that these two buttons don’t toggle the bold and the italic attribute; if the selected text is already bold, nothing will change.

The Clear button clears the contents of the control by calling its Clear method:

RichTextBox1.Clear()

The two buttons on the second row demonstrate the nature of the RichTextBox control. Select a few words on the control, turn on their bold and/or italic attribute, and then click the Show Text button. You’ll see a message box that contains the control’s text. No matter how the text is formatted, the control’s Text property will be the same. This is the text you would copy from the control and paste into a text-editing application that doesn’t support formatting commands (for example, Notepad). The code behind the Show Text button is:

MsgBox(RichTextBox1.Text)

To replace the text on the control, you can either type some new text, or select some formatted text in another application, like WordPad, and paste it on the control.

The RTF Code

If you click the Show RTF button, you’ll see the actual RTF code that produced the formatted document in Figure 7.11. The message box with the RTF code is shown in Figure 7.12. This is all the information the RichTextBox control requires to render the document. As complicated as it may look, it isn’t difficult to produce. In programming the RichTextBox control, you’ll rarely have to worry about inserting actual RTF tags in the code. The control is responsible for generating the RTF code and for rendering the document. You simply manipulate a few properties (the recurring theme in Visual Basic programming), and the control does the rest.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

310 Chapter 7 MORE WINDOWS CONTROLS

Figure 7.12

The RTF code for the formatted document shown in Figure 7.11

On rather rare occasions, you may have to supply RTF tags. You don’t have to know much about RTF tags, though. Simply format a few words with the desired attributes using the RTFDemo application (or experiment with the Immediate window), copy the tags that produce the desired result, and use them in your application. If you are curious about RTF, experiment with the RTFDemo application.

One of the most interesting applications on the book’s CD-ROM is the RTFPad application, a word-processing application that’s discussed in detail later in this chapter. This application duplicates much of the functionality of Windows WordPad, but it’s included in this book to show you how the RichTextBox control is used. The RTFPad application can become your starting point for writing custom word-processing applications (a programmer’s text editor with color-coded keywords, for example).

The RichTextBox’s Properties

The names of the RichTextBox control’s properties for manipulating selected text mostly start with Selected or Selection. The most commonly used properties related to the selected text are shown in Table 7.1. Some of these are discussed in further detail in following sections.

Table 7.1: RichTextBox Properties for Manipulating Selected Text

Property

What It Manipulates

SelectedText

The selected text

SelectedRTF

The RTF code of the selected text

SelectionStart

The position of the selected text’s first character

SelectionLength

The length of the selected text

SelectionFont

The font of the selected text

SelectionColor

The color of the selected text

SelectionIndent, SelectionRightIndent,

The indentation of the selected text

SelectionHangingIndent

 

RightMargin

The distance of the text’s right margin from the left edge of the

 

control, which is in effect the length of each text line

SelectionBullet

Whether the selected text is bulleted

BulletIndent

The amount of bullet indent for the selected text

 

 

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE RICHTEXTBOX CONTROL 311

SelectedText

The SelectedText property represents the selected text. To assign the selected text to a variable, use the following statement:

SText=RichTextbox1.SelectedText

RichTextbox1 is the name of the control. You can also modify the selected text by assigning a new value to the SelectedText property. The following statement converts the selected text to uppercase:

RichTextbox1.SelectedText=UCase(RichTextbox1.SelectedText)

If you assign a string to the SelectedText property, the selected text in the control is replaced with the string. The following statement replaces the current selection on the RichTextbox1 control with the string “Revised string”:

RichTextbox1.SelectedText=”Revised string”

If no text is selected, the statement inserts the string at the location of the pointer. It is possible, therefore, to insert text automatically by assigning a string to the SelectedText property.

Note The SelectedText property is similar to the Text property. The difference is that SelectedText applies to the current selection or cursor position instead of the entire text of the control. The same is true for the RTF and SelectedRTF properties.

SelectionStart, SelectionLength

To simplify the manipulation and formatting of the text on the control, two additional properties, SelectionStart and SelectionLength, report the position of the first selected character in the text and the length of the selection, respectively. You can also set the values of these properties to select a piece of text from within your code. One obvious use of these properties is to select (and highlight) the entire text (or a segment of the text):

RichTextBox1.SelectionStart = 0

RichTextBox1.SelectionLength = Len(RichTextBox1.Text)

A better method of selecting the entire text on the control is to call the SelectAll method, which is discussed later in this section.

SelectionAlignment

Use this property to read or change the alignment of one or more paragraphs. This property value is one of the members of the HorizontalAlignment enumeration: Left, Right, and Center.

Note The user doesn’t have to actually select the entire paragraph to align it. Placing the pointer anywhere in the paragraph or selecting a few characters in the paragraph will do, because there is no way to align only a part of a paragraph.

SelectionIndent, SelectionRightIndent, SelectionHangingIndent

These properties allow you to change the margins of individual paragraphs. The SelectionIndent property sets (or returns) the amount of the text’s indentation from the left edge of the control. The

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

312 Chapter 7 MORE WINDOWS CONTROLS

SelectionRightIndent property sets (or returns) the amount of the text’s indentation from the right edge of the control. The SelectionHangingIndent property is the distance between the left edge of the first line and the left edge of the following lines.

The SelectionHangingIndent property includes the current setting of the SelectionIndent property. If all the lines of a paragraph are aligned to the left, the SelectionIndent property can have any value (this is the distance of all lines from the left edge of the control), but the SelectionHangingIndent property must be zero. If the first line of the paragraph is shorter than the following lines, the SelectionHangingIndent has a negative value. Figure 7.13 shows two differently formatted paragraphs. The settings of the SelectionIndent and SelectionHangingIndent properties are determined by the two sliders at the top of the form.

Figure 7.13

Various combinations of the SelectionIndent and SelectionHangingIndent properties produce all possible paragraph formatting.

SelectionBullet, BulletIndent

You use these properties to create a list of bulleted items. If you set the SelectionBullet property to True, the selected paragraphs are formatted with a bullet style, similar to the <ul> tag in HTML. To create a list of bulleted items, assign the value True to the SelectionBullet property. To change a list of bulleted items back to normal text, make the same property False.

The paragraphs formatted with the SelectionBullet property set to True are also indented from the left by a small amount. To set the amount of the indentation, use the BulletIndent property, whose syntax is

RichTextBox1.BulletIndent = value

You can also read the BulletIndent property from within your code to find out the bulleted items’ indentation. Or you can use this property, along with the SelectionBullet property, to simulate nested bulleted items. If the current selection’s SelectionBullet property is True and the user wants to apply the bullet format, you can increase the indentation of the current selection.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com