- •Using Your Sybex Electronic Book
- •Acknowledgments
- •Contents at a Glance
- •Introduction
- •Who Should Read This Book?
- •How About the Advanced Topics?
- •The Structure of the Book
- •How to Reach the Author
- •The Integrated Development Environment
- •The Start Page
- •Project Types
- •Your First VB Application
- •Making the Application More Robust
- •Making the Application More User-Friendly
- •The IDE Components
- •The IDE Menu
- •The Toolbox Window
- •The Solution Explorer
- •The Properties Window
- •The Output Window
- •The Command Window
- •The Task List Window
- •Environment Options
- •A Few Common Properties
- •A Few Common Events
- •A Few Common Methods
- •Building a Console Application
- •Summary
- •Building a Loan Calculator
- •How the Loan Application Works
- •Designing the User Interface
- •Programming the Loan Application
- •Validating the Data
- •Building a Math Calculator
- •Designing the User Interface
- •Programming the MathCalculator App
- •Adding More Features
- •Exception Handling
- •Taking the LoanCalculator to the Web
- •Working with Multiple Forms
- •Working with Multiple Projects
- •Executable Files
- •Distributing an Application
- •VB.NET at Work: Creating a Windows Installer
- •Finishing the Windows Installer
- •Running the Windows Installer
- •Verifying the Installation
- •Summary
- •Variables
- •Declaring Variables
- •Types of Variables
- •Converting Variable Types
- •User-Defined Data Types
- •Examining Variable Types
- •Why Declare Variables?
- •A Variable’s Scope
- •The Lifetime of a Variable
- •Constants
- •Arrays
- •Declaring Arrays
- •Initializing Arrays
- •Array Limits
- •Multidimensional Arrays
- •Dynamic Arrays
- •Arrays of Arrays
- •Variables as Objects
- •So, What’s an Object?
- •Formatting Numbers
- •Formatting Dates
- •Flow-Control Statements
- •Test Structures
- •Loop Structures
- •Nested Control Structures
- •The Exit Statement
- •Summary
- •Modular Coding
- •Subroutines
- •Functions
- •Arguments
- •Argument-Passing Mechanisms
- •Event-Handler Arguments
- •Passing an Unknown Number of Arguments
- •Named Arguments
- •More Types of Function Return Values
- •Overloading Functions
- •Summary
- •The Appearance of Forms
- •Properties of the Form Control
- •Placing Controls on Forms
- •Setting the TabOrder
- •VB.NET at Work: The Contacts Project
- •Anchoring and Docking
- •Loading and Showing Forms
- •The Startup Form
- •Controlling One Form from within Another
- •Forms vs. Dialog Boxes
- •VB.NET at Work: The MultipleForms Project
- •Designing Menus
- •The Menu Editor
- •Manipulating Menus at Runtime
- •Building Dynamic Forms at Runtime
- •The Form.Controls Collection
- •VB.NET at Work: The DynamicForm Project
- •Creating Event Handlers at Runtime
- •Summary
- •The TextBox Control
- •Basic Properties
- •Text-Manipulation Properties
- •Text-Selection Properties
- •Text-Selection Methods
- •Undoing Edits
- •VB.NET at Work: The TextPad Project
- •Capturing Keystrokes
- •The ListBox, CheckedListBox, and ComboBox Controls
- •Basic Properties
- •The Items Collection
- •VB.NET at Work: The ListDemo Project
- •Searching
- •The ComboBox Control
- •The ScrollBar and TrackBar Controls
- •The ScrollBar Control
- •The TrackBar Control
- •Summary
- •The Common Dialog Controls
- •Using the Common Dialog Controls
- •The Color Dialog Box
- •The Font Dialog Box
- •The Open and Save As Dialog Boxes
- •The Print Dialog Box
- •The RichTextBox Control
- •The RTF Language
- •Methods
- •Advanced Editing Features
- •Cutting and Pasting
- •Searching in a RichTextBox Control
- •Formatting URLs
- •VB.NET at Work: The RTFPad Project
- •Summary
- •What Is a Class?
- •Building the Minimal Class
- •Adding Code to the Minimal Class
- •Property Procedures
- •Customizing Default Members
- •Custom Enumerations
- •Using the SimpleClass in Other Projects
- •Firing Events
- •Shared Properties
- •Parsing a Filename String
- •Reusing the StringTools Class
- •Encapsulation and Abstraction
- •Inheritance
- •Inheriting Existing Classes
- •Polymorphism
- •The Shape Class
- •Object Constructors and Destructors
- •Instance and Shared Methods
- •Who Can Inherit What?
- •Parent Class Keywords
- •Derived Class Keyword
- •Parent Class Member Keywords
- •Derived Class Member Keyword
- •MyBase and MyClass
- •Summary
- •On Designing Windows Controls
- •Enhancing Existing Controls
- •Building the FocusedTextBox Control
- •Building Compound Controls
- •VB.NET at Work: The ColorEdit Control
- •VB.NET at Work: The Label3D Control
- •Raising Events
- •Using the Custom Control in Other Projects
- •VB.NET at Work: The Alarm Control
- •Designing Irregularly Shaped Controls
- •Designing Owner-Drawn Menus
- •Designing Owner-Drawn ListBox Controls
- •Using ActiveX Controls
- •Summary
- •Programming Word
- •Objects That Represent Text
- •The Documents Collection and the Document Object
- •Spell-Checking Documents
- •Programming Excel
- •The Worksheets Collection and the Worksheet Object
- •The Range Object
- •Using Excel as a Math Parser
- •Programming Outlook
- •Retrieving Information
- •Recursive Scanning of the Contacts Folder
- •Summary
- •Advanced Array Topics
- •Sorting Arrays
- •Searching Arrays
- •Other Array Operations
- •Array Limitations
- •The ArrayList Collection
- •Creating an ArrayList
- •Adding and Removing Items
- •The HashTable Collection
- •VB.NET at Work: The WordFrequencies Project
- •The SortedList Class
- •The IEnumerator and IComparer Interfaces
- •Enumerating Collections
- •Custom Sorting
- •Custom Sorting of a SortedList
- •The Serialization Class
- •Serializing Individual Objects
- •Serializing a Collection
- •Deserializing Objects
- •Summary
- •Handling Strings and Characters
- •The Char Class
- •The String Class
- •The StringBuilder Class
- •VB.NET at Work: The StringReversal Project
- •VB.NET at Work: The CountWords Project
- •Handling Dates
- •The DateTime Class
- •The TimeSpan Class
- •VB.NET at Work: Timing Operations
- •Summary
- •Accessing Folders and Files
- •The Directory Class
- •The File Class
- •The DirectoryInfo Class
- •The FileInfo Class
- •The Path Class
- •VB.NET at Work: The CustomExplorer Project
- •Accessing Files
- •The FileStream Object
- •The StreamWriter Object
- •The StreamReader Object
- •Sending Data to a File
- •The BinaryWriter Object
- •The BinaryReader Object
- •VB.NET at Work: The RecordSave Project
- •The FileSystemWatcher Component
- •Properties
- •Events
- •VB.NET at Work: The FileSystemWatcher Project
- •Summary
- •Displaying Images
- •The Image Object
- •Exchanging Images through the Clipboard
- •Drawing with GDI+
- •The Basic Drawing Objects
- •Drawing Shapes
- •Drawing Methods
- •Gradients
- •Coordinate Transformations
- •Specifying Transformations
- •VB.NET at Work: Plotting Functions
- •Bitmaps
- •Specifying Colors
- •Defining Colors
- •Processing Bitmaps
- •Summary
- •The Printing Objects
- •PrintDocument
- •PrintDialog
- •PageSetupDialog
- •PrintPreviewDialog
- •PrintPreviewControl
- •Printer and Page Properties
- •Page Geometry
- •Printing Examples
- •Printing Tabular Data
- •Printing Plain Text
- •Printing Bitmaps
- •Using the PrintPreviewControl
- •Summary
- •Examining the Advanced Controls
- •How Tree Structures Work
- •The ImageList Control
- •The TreeView Control
- •Adding New Items at Design Time
- •Adding New Items at Runtime
- •Assigning Images to Nodes
- •Scanning the TreeView Control
- •The ListView Control
- •The Columns Collection
- •The ListItem Object
- •The Items Collection
- •The SubItems Collection
- •Summary
- •Types of Errors
- •Design-Time Errors
- •Runtime Errors
- •Logic Errors
- •Exceptions and Structured Exception Handling
- •Studying an Exception
- •Getting a Handle on this Exception
- •Finally (!)
- •Customizing Exception Handling
- •Throwing Your Own Exceptions
- •Debugging
- •Breakpoints
- •Stepping Through
- •The Local and Watch Windows
- •Summary
- •Basic Concepts
- •Recursion in Real Life
- •A Simple Example
- •Recursion by Mistake
- •Scanning Folders Recursively
- •Describing a Recursive Procedure
- •Translating the Description to Code
- •The Stack Mechanism
- •Stack Defined
- •Recursive Programming and the Stack
- •Passing Arguments through the Stack
- •Special Issues in Recursive Programming
- •Knowing When to Use Recursive Programming
- •Summary
- •MDI Applications: The Basics
- •Building an MDI Application
- •Built-In Capabilities of MDI Applications
- •Accessing Child Forms
- •Ending an MDI Application
- •A Scrollable PictureBox
- •Summary
- •What Is a Database?
- •Relational Databases
- •Exploring the Northwind Database
- •Exploring the Pubs Database
- •Understanding Relations
- •The Server Explorer
- •Working with Tables
- •Relationships, Indices, and Constraints
- •Structured Query Language
- •Executing SQL Statements
- •Selection Queries
- •Calculated Fields
- •SQL Joins
- •Action Queries
- •The Query Builder
- •The Query Builder Interface
- •SQL at Work: Calculating Sums
- •SQL at Work: Counting Rows
- •Limiting the Selection
- •Parameterized Queries
- •Calculated Columns
- •Specifying Left, Right, and Inner Joins
- •Stored Procedures
- •Summary
- •How About XML?
- •Creating a DataSet
- •The DataGrid Control
- •Data Binding
- •VB.NET at Work: The ViewEditCustomers Project
- •Binding Complex Controls
- •Programming the DataAdapter Object
- •The Command Objects
- •The Command and DataReader Objects
- •VB.NET at Work: The DataReader Project
- •VB.NET at Work: The StoredProcedure Project
- •Summary
- •The Structure of a DataSet
- •Navigating the Tables of a DataSet
- •Updating DataSets
- •The DataForm Wizard
- •Handling Identity Fields
- •Transactions
- •Performing Update Operations
- •Updating Tables Manually
- •Building and Using Custom DataSets
- •Summary
- •An HTML Primer
- •HTML Code Elements
- •Server-Client Interaction
- •The Structure of HTML Documents
- •URLs and Hyperlinks
- •The Basic HTML Tags
- •Inserting Graphics
- •Tables
- •Forms and Controls
- •Processing Requests on the Server
- •Building a Web Application
- •Interacting with a Web Application
- •Maintaining State
- •The Web Controls
- •The ASP.NET Objects
- •The Page Object
- •The Response Object
- •The Request Object
- •The Server Object
- •Using Cookies
- •Handling Multiple Forms in Web Applications
- •Summary
- •The Data-Bound Web Controls
- •Simple Data Binding
- •Binding to DataSets
- •Is It a Grid, or a Table?
- •Getting Orders on the Web
- •The Forms of the ProductSearch Application
- •Paging Large DataSets
- •Customizing the Appearance of the DataGrid Control
- •Programming the Select Button
- •Summary
- •How to Serve the Web
- •Building a Web Service
- •Consuming the Web Service
- •Maintaining State in Web Services
- •A Data-Driven Web Service
- •Consuming the Products Web Service in VB
- •Summary
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 |