Platinum Edition Using Visual Basic 5

Previous chapterNext chapterContents


- 14 -
Working with Text, Fonts, and Colors

You will see how to display text on-screen through the use of the TextBox and Masked Edit controls.
You will learn about some of the many functions available in Visual Basic for working with text.
You will explore the use of the Font object's properties in your programs.
You will see how to use the RichTextBox control to create a simple word processor that enables your users to control the appearance of the text that they enter.
You can use a variety of colors to display text and other objects on-screen and on color printers. You will see how the color of the text is controlled.

The vast majority of your programs will use text as the primary means of communicating information to the users. "Text" refers not only to text displayed on-screen in controls, but also to text that is stored and created in your program code. To write almost any program in Visual Basic, you need to know how to work with text. In earlier chapters, you learned about displaying text in labels and text boxes. This chapter expands on that knowledge by showing you how properties and functions are used to manipulate text. You also see how to change the appearance of your text by using fonts and colors in your programs.

Getting and Displaying Text

Two of the primary tasks of any program are to retrieve information from the user and to display information to the user. This information is often in the form of text and can be something as simple as the names in a membership list, or something as complex as developing a specialized word processor for a particular industry. Visual Basic provides a number of ways to input and display information. For input, the primary control is the text box, but there are several other controls covered in this chapter. For output, you can display information on-screen by using the TextBox and Label controls, or you can print information directly on a Form object or to the Printer object. This chapter sticks with using the controls; printing is covered in Chapter 15, "Displaying and Printing Reports."

Reviewing the Basic Controls

In Chapter 4, "Working with Forms and Controls," you were introduced to the TextBox and Label controls. As you probably remember, the label can display text to the user, whether the text was entered into the label at design time or assigned with code to the label's Caption property at runtime. The Label control can display a single line of text or multiple lines easily, but it does not allow the user to input text or scroll through the text if there is more than would fit in the control.

The text box, on the other hand, can do everything a label can do--and it allows editing and scrolling. Using a text box, users can enter anything they want, and your program can retrieve this information through the Text property. Your program can also set the Text property to display information back to the user.

Using Other Features of the TextBox Control

In addition to the text box's standard properties, there are several other properties and features of the text box that make it even more versatile. Some key additional properties are the following:

Locking Out the User First, take a look at the Locked property. Its purpose is to enable you to use the TextBox control for display only. When this property is set to True, no editing can be performed in the text box. One example of using the Locked property is the display of a large amount of text in a text box with scroll bars. This permits users to scroll through the information, but prevents them from changing it. Even when a text box is locked, however, the user can select text and copy it to the Windows Clipboard by right-clicking it and selecting Copy from the context menu that appears.


NOTE: Do not confuse the Locked property with the Enabled property. Setting the Locked property to True does not create the "grayed-out" effect. It prevents users from modifying your text, but it still allows them to select and copy text from the text box to the Windows Clipboard. Text in text boxes whose Enabled property is set to False cannot be selected; therefore, it cannot be copied to the Windows Clipboard.

There is nothing special involved in using the Locked property; it can be set to True or False in code, as follows:

txtTest.Locked = True
txtTest.Text = "You can't edit this!"

One obvious use of the Locked property is to prevent a user from accidentally changing the information in a text box. In this case, you could place a command button on the form that the user must click to be allowed to edit the information on the screen. For example, suppose your Personnel department frequently needs to look up information on employees. A locked text box will prevent accidental editing of this information. This example is shown in Figure 14.1.

FIG. 14.1
Using the Locked property prevents inadvertent editing of text. Notice in the pop-up menu (automatically implemented by Windows), only the Copy option is available for a locked text box.

One way to process a bunch of text boxes as a group is to use a control array, which enables you to use a For loop rather than list each text box individually. In this case, code could be written in the command button's Click event procedure to change the Locked property from True to False as follows:

Private Sub cmdEdit_Click()
  Dim I As Integer
  For I = 0 To 5
   txtInfo(I).Locked = False
 ext I
End Sub

Another way to change the Locked property on a bunch of text boxes is to use a For Each loop. This works even when your text boxes are not in a control array:

Private Sub cmdEdit_Click()
    Dim objControl As Control
    
    For Each objControl In Me.Controls
        If TypeOf objControl Is TextBox Then objControl.Locked = True
   ext objControl
End Sub

Notice that the For Each structure in this code works with any property or control, not just the Locked property. Also notice that a real-life version of the program probably would check the security level of the user before allowing the edit.

Placing a Limit on Characters Although typically you think of the text box as handling any amount of text, there are times when you will want to limit the amount of text that a user can enter. You can handle this by using the MaxLength property of the text box control. The purpose of this property is to restrict the number of characters that the user can enter. There are a number of reasons that you might want to limit the number of characters a user can enter. In many programs, you will be dealing with IDs that are a fixed length. For example, an inventory program might use numbers that are 10 characters long for their parts, or a personnel information system might use social security numbers, which are, by definition, nine digits long.

Another need to limit the length of a text field occurs when working with database files. Most fields in a database file have a specific length. If you allow your user to enter more characters than can be stored in the field, information may be lost, or an error may be generated.

Setting the maximum number of characters is quite easy. Just select the MaxLength property of the text box and type in a number. If you want to permit the user to enter an unlimited number of characters, then enter 0 (the default setting) for the value.


NOTE: The amount of text that the user can enter is not really unlimited. A text box whose MultiLine property is set to True can handle a maximum of about 32,000 characters; single-line text boxes are limited by system memory constraints.

So what happens when the user is entering data and gets to the maximum number of characters? At that point, the text box stops accepting additional characters and beeps each time another character is typed. You can try this for yourself. Place a text box on a form and set the MaxLength property to 10. Then, run the program and start typing in the letters of the alphabet. You will see that A-J are accepted, but when you try to type in the k, the text box does not accept it. This occurs even if you have sized the control so that there is plenty of additional space to the right of the text you entered.

Hiding the Contents If you are using a text box as part of a login form, you will want the ability to hide the password that is entered by the user. To do this, simply enter a character in the PasswordChar property of the text box. This changes the text box's display behavior so that the password character is substituted for each character in the Text property. You may have seen this effect many times when logging in to Windows or to your company's network. Note that the contents of the Text property still reflect what is actually typed by the user, and your code always sees the "real" text. Although you can enter any character, it is customary to use the asterisk (*) character for hiding text (see Figure 14.2).

FIG. 14.2
Avoid prying eyes by using the PasswordChar property.

Editing Text in a Text Box Thus far, you have looked at how to create various types of text boxes, but how can users edit what they've entered? Are they limited just to typing information? Fortunately, no. If you have used any Windows word processor, you are already familiar with how to edit the text in a text box. Just as with a word processor, users can use ordinary keys, such as Delete and Backspace, and they can highlight text with the mouse or by using Shift with the cursor keys. They then can cut (Ctrl+X), copy (Ctrl+C), or paste (Ctrl+V) text and even undo their last change by pressing Ctrl+Z. Using these techniques, they can remove or change text and move text around within a text box or between text boxes (see Figure 14.3).

FIG. 14.3
Your users can copy text from one text box and paste it into another.


TIP: To select a single word in a text box, double-click the word. You can also use a combination of Shift, Ctrl, and the arrow keys to highlight a word at a time.

Windows also provides a pop-up menu for editing use. The user can simply highlight some text in a text box and right-click the text box. A pop-up menu opens containing the Cut, Copy, Paste, and Delete commands, as well as a Select All option. This menu also has an Undo command users can employ to reverse a change, though it's active only when no text is selected.

You already know that the Text property contains all the text in a text box. Suppose a user has selected some text in a text box, and you want to manipulate only that text. The selected text is identified by three properties:

You can use these properties to work with a selected piece of text in your program. Look at the example in Figure 14.3. In this case, the SelText property would contain just the phrase "a selection of text." The SelLength property would contain the integer value 19, which is the length of that string. And the SelStart property would contain the integer value 29, which means the selected phrase starts with the 29th character in the text box.

In addition to determining what has been selected, you can also set the properties from code to alter the selection. Every time you set the SelStart property, you must set the SelLength property to highlight some characters. To select the first three characters, you could use this code:

txtTest.SelStart = 0
txtTest.SelLength = 3

The SelLength property can be changed multiple times. This will cause the selection to increase or decrease in size, automatically updating the SelText property. Setting the SelText property from code causes the currently selected text to be replaced with a new string, for example:

txtTest.SelText = "jumped into oncoming traffic."

One use of these properties is to highlight the entire contents of a text box. Suppose, for example, that you have populated some text boxes for a user to edit. When the user presses the Tab key to move to a text box, you might want to highlight whatever is in the text box automatically (this is a Windows standard). This way, the user can start typing immediately, automatically deleting the existing text. This is illustrated in the following code for a text box's GotFocus event:

Private Sub txtSelect_GotFocus()
  With txtSelect
   .SelStart = 0
   .SelLength = Len(.Text)
  End With
End Sub


NOTE: The first character in a text box has an index value of 0.

Although the text box is great, you can't perform the drag-and-drop editing that you find in some newer word processors. You are also limited to one font and one color of text within each text box. If you require formatting capabilities that are more advanced, you'll probably find what you're looking for in the Masked Edit control described in the next section.

Limiting Text with the Masked Edit Control

Although limiting the umber of characters that a user can enter is one way of controlling the input, it often is also necessary to control the type of characters that can be entered (such as letters, digits, or punctuation marks). In addition, there may be times when you want to change the appearance of the text box to include familiar placeholders for data entry, such as parentheses in a phone number or hyphens in a social security number. You could use a standard text box and program code to accomplish this, but there is an easier way.

Visual Basic provides a number of custom controls that are not among the standard set present when you start Visual Basic. Among these is the Masked Edit control. This control enables you to specify the number, type, and position of characters in the data entry field. It also enables you to use placeholder characters within the field. Figure 14.4 illustrates two examples of the Masked Edit control after the user has entered text. Note that they look like ordinary text boxes; however, the masked edit capability of the controls have helped ensure that the data entered conforms to the program's needs.

FIG. 14.4
The Masked Edit control provides considerable control over the number, type, and position of characters in a text field, although it looks to the user just like a normal text box.

Adding the Masked Edit Control to Your Project Because the Masked Edit control is not part of the standard control Toolbox, the first step in using the control is to instruct Visual Basic to make the control available to you. Choose Project, Components to open the Components dialog box. After you are in the dialog box, click the box next to Microsoft Masked Edit Control 5.0 and click Apply or OK to add the control to the Toolbox (see Figure 14.5).


TIP: You can also access the Components dialog box by pressing Ctrl+T or by right-clicking the Toolbox.

Now that you have added the Masked Edit control to the Toolbox, you are ready to work with it in your program. As with any other control, to add a Masked Edit control to your form, you select its tool in the Toolbox and then draw it on the form where you want it to appear. A Masked Edit control supports only one line of input, so you need to draw it wide enough to contain all the characters to be entered.


NOTE: The Masked Edit control is capable of handling a maximum of 64 characters. Although this is quite sufficient for most needs, if your program requires a larger field, you have to use a standard text box and control the formatting with code.

FIG. 14.5
Any control that displays a check mark next to its name will appear in the Toolbox.

Allowing Only Certain Characters The purpose of the Masked Edit control is to make sure data is entered in a specific format. Suppose, for example, you put a text box on a form and ask the user to enter a date. One user might use a date format with slashes--12/7/41, for example--whereas another might spell it out--Dec. 7, 1941. The same type of inconsistent input could occur with phone numbers or dollar amounts, among others. You could handle this in code by validating the information before processing it. However, using the Masked Edit control is a cleaner way to do this because it requires no code. With this control, you can specify which characters are allowable and where they are placed in a field. The Masked Edit control has a Mask property that allows you to tell the control where you want specific characters placed. The Mask property is a string that represents a template of what the text input should look like; for example, ###-#### represents seven numbers with a dash after the third number. The # is a special character code, which means only an integer (0-9) can be entered at this location.

The character codes also specify how many characters can be entered in the field. If you put only five character codes in the mask, then no more than five characters can be entered by the user. Table 14.1 shows some of the different character codes that can be used in the Masked Edit control.

Table 14.1 Specify the Characters to Be Entered Using the Mask Property

Mask Code Allowable Characters
# Any digit 0-9, space, plus or minus (+ or -) signs
? Any letter a-z or A-Z
A Any letter or digit
& Any character or space

If the Mask property is blank (which is the default setting), then the Masked Edit control behaves like a simple text box.


NOTE: A complete list of allowable character codes is listed in Visual Basic's help system under "Mask property." Take a moment to go over this list, which includes number placeholders and optional masks.

By using the Mask property, you can develop input masks for almost any type of data. For example, the mask for a five-digit ZIP code would be #####, or a ZIP+4 code would be entered as #####-####. If you wanted a mask for two-letter state abbreviations, you would use ??. The great thing about this control is that it relieves the developer from some extra coding.

If the user "violates" the mask rules, then the Masked Edit box beeps; the user cannot continue entering text unless it is correct. For example, if the mask is ####, no characters will be displayed until a number is entered. Optional masks, such as 9 for optional numbers, produce a different effect. For example, the mask ?9? would accept either two letters in a row or a number surrounded by two letters.

Keeping Your Place in the Field Character codes are not the only things that you can enter in the Mask property. You can also place any other characters in the mask for use as placeholders. These characters include (but are not limited to) asterisks (*), dollar signs ($), parentheses, hyphens, and commas. For example, the typical notation for a phone number is (212) 555-1234. Within this notation, the parentheses, space, and hyphen are all placeholders. To represent this in an input mask, you would set the Mask property to (###) ###-####. As a user types a phone number, the first three numbers are entered between the parentheses; then the input skips to the third location in front of the hyphen. In other words, the masked input control automatically skips the placeholders. By using the character codes and placeholders, you can create many kinds of custom input fields. A few examples are shown in Table 14.2.

Table 14.2 Create Many Types of Input Masks with Character Codes and Placeholders

Desired Input Mask Example
ZIP Code ##### 35242
Phone Number (###) ###-#### (205) 555-7575
Social Security Number ###-##-#### 123-45-6789
Month-Day-Year AAA ##, #### Feb 18, 1998
Date ##/##/## 02/18/98
Time ##:## AA 02:31 pm

Figure 14.6 shows how the Masked Edit control appears before the user types any text in it. Notice that there are underscore (_) characters in every location that you had entered a character code in the Mask property. This tells you, or the user, what locations are available for typing. The character used to indicate these input positions is contained in the PromptChar property. The default value of this property is the underscore, but you can change it to any other character you want, for example, # for a phone number.

FIG. 14.6
Use the PromptChar property to specify which character to use to indicate input positions.

Getting the Information from the Masked Edit Control Like the text box, the Masked Edit control supports both the Text and SelText properties. This lets you access the entire contents of the field, or just a selected portion. There are a few differences in the behavior of these properties of which you should be aware. The Text property contains all the information that the user entered, plus any placeholder characters that were in the Mask property. For example, the phone number mask that was used earlier contained parentheses, a space, and a hyphen ((###) ###-####). When a user enters a phone number, only the digits are entered, but the Text property contains all the digits and the placeholders. That is, if the user entered 2055550770, the Text property would contain (205) 555-0770.

There is also another property that can be used to reference the information in the Masked Edit control. This property is the ClipText property. This property, in conjunction with the ClipMode property, enables you to retrieve only the information that the user typed, with or without the placeholder characters. The ClipMode property has two settings, 0-mskIncludeLiterals and 1-mskExcludeLiterals. By setting this property to mskExcludeLiterals, you can retrieve just the user information, with no placeholder characters. Figure 14.7 shows the difference between the information retrieved with the Text and ClipText properties.

FIG. 14.7
The Text and ClipText properties return different parts of the entered information.

Why is the ClipText property important? Because with many types of numerical entries, such as dates, times, and phone numbers, you want to provide the placeholders for easy data entry by users, but you do not want to store the numbers with all the placeholders. Also, the Mask property can display numbers with commas separating the thousands, millions, and other groups (such as 1,000,000). When the number is used for calculations, you cannot have the commas present.


TIP: The Masked Edit box's beep may not be informative enough for users to correct invalid keystrokes, in which case you might want to use the control's ValidationError event. For example, if the mask is ## and the user types an A, then the ValidationError event occurs. You could add code to this event to inform the user of the proper formatting.

Modifying Text with a Program

Although the text box allows the user to enter and edit text, you will also have many occasions in which you need to modify text strings within your program. Visual Basic provides a number of functions that are useful in modifying text. These functions are as follows:


NOTE: All of the functions in this list (except Len) return a Variant data type. For each of them, there is an identical function with a dollar sign ($) at the end of the function's name to indicate a String type return value. I recommend using the $ versions (such as Left$) whenever possible because they are more efficient. For the sake of readability, the Variant versions are used in this chapter.

In addition, Visual Basic has the concatenation operator and the ampersand (&), which enables you to combine strings. This section explains how to use these various functions in your program. The concatenation operator was covered in Chapter 8, "Programming Basics." If you need to refresh your memory about its use, please refer to that chapter.

See "Working with Strings," Chapter 9

Changing the Case of Letters

There are two functions that can modify the case of letters in a string: UCase and LCase. The UCase function returns a string with all the letters converted to uppercase (capital) letters. The LCase function does just the opposite, converting the entire string to lowercase letters.

Although these may appear to be somewhat trivial functions, they actually are quite useful for a number of tasks. First, you can use the functions to properly capitalize names or other words that a user may enter. The code in Listing 14.1 capitalizes the first letter of a word and makes the rest of the word lowercase.

Listing 14.1 CASES.FRM--Using UCase and LCase to Properly Capitalize a Word

Dim lcWord, as String, ProperWord as String, WordLen As Integer
lcWord = LCase(lcWord)
WordLen = Len(lcWord)
ProperWord = UCase(Left(lcWord, 1)) & Right(lcWord, WordLen - 1)

These functions are useful, for example, when comparing user input to a predefined value or a range of values. If we convert the user's input to uppercase, we can compare it to an uppercase test string, as in the following example:

Select Case UCase(txtOperation.Text)
   Case "WASH"
     ` Do Something
   Case "RINSE"
     ` Do Something Else
   Case "SPIN"
     ` Do Something Else Yet
   Case Else
      MsgBox "Invalid Entry!"
End Select

In the code above, if the UCase function had not been used, then the user would receive the Invalid Entry message even if he had entered a "correct" choice in lowercase or mixed case ("Rinse", for example).

Another Visual Basic function, StrConv, performs special conversions of strings. Most of the conversions it can perform are either redundant (converting to all uppercase or all lowercase, for example) or beyond the scope of this book (converting between different types of Japanese characters), but one of its conversion types is worth mentioning here. StrConv can convert a string to proper case, where the first letter of each word is capitalized. The following code sample demonstrates this technique:

lblHeadline = StrConv(stHeadline, vbProperCase)

Examples of using UCase and LCase, as well as StrConv, are illustrated in Figure 14.8.

FIG. 14.8
LCase, UCase, and StrConv can be used to modify the case of the letters in a string of text.

Chapter 10, "Managing Your Project," provides more information on functions and their uses.

See "Using Procedures and Functions," Chapter 17

Getting Pieces of a String

Look at the following code from Listing 14.1 again. In addition to using just the UCase and LCase functions, it also uses several functions to extract pieces of text from the original string. This illustrates one of the more important tasks involved in manipulating strings--the capability to add, remove, or change single characters, words, or sections of a string.

Dim lcWord, as String, ProperWord as String, WordLen As Integer
lcWord = LCase(lcWord)
WordLen = Len(lcWord)
ProperWord = UCase(Left(lcWord, 1)) & Right(lcWord, WordLen - 1)

Visual Basic provides a number of functions that are designed for string manipulations. There are functions that add and remove spaces, a function for determining the length of a string, a function for performing a search, and a function for exchanging one piece of a string for another string.

Determining What Is in the String For many string-related tasks, the first programming requirement is to determine if a word, phrase, or other group of characters exists in a string, and if so, where. The capability to find one string within another enables you to perform word searches within text. This can be used to perform a global replacement of a string, such as replacing the word "text" with the word "string" throughout a word-processing document. Another, more common, reason for searching within a string is parsing the string. For example, suppose you have an input string that contains a person's name in this format: "Dr. Stirling P. Williams, Jr." If you have a file of a hundred such strings, putting this information into a database with separate first and last name fields would be a little difficult. However, you could use a string search function along with a little program logic to parse the string into smaller pieces. The function that enables you to search a string for a character or group of characters is the InStr function. This function has two required and two optional parameters. The required parameters are the string to be searched and the text to search for. If the search text appears in the string being searched, InStr returns the index of the character where the search string starts. If the search text is not present, InStr returns 0. The simple syntax of the InStr function is shown here:

chrpos = InStr(sourcestr, searchstr)

For example, the function call

Print Instr("I'll see you next Tuesday.","you")

would print a result of 10 because that is the position where the word "you" begins.

The first optional parameter of the InStr function tells the function the character position from which to start the search. This position must be a positive integer. If the starting position is greater than the length of the string, InStr will return 0. This syntax of the InStr function is as follows:

chrpos = InStr(StartPos, sourcestr, searchstr)

For example, the function call

Print Instr(7,"Pride cometh before a fall","e")

would return the value of 10, even though the first "e" in the string is at position 5, because the search starts from position 7.

The other optional parameter determines whether the search to be performed is case-sensitive (uppercase and lowercase letters do not match) or case-insensitive. Setting the value of the comparison parameter to 0, its default value, performs a case-sensitive search. Setting the value to 1 performs a case-insensitive search. This syntax is shown here:

chrpos = InStr(StartPos, sourcestr, searchstr, 1)

Note that with the optional parameters, you can write code that will find each successive search string in your text. The code in Listing 14.2 will print the words in a string that are separated by spaces. It works by taking the result of the Instr function and passing it back in to the StartPos parameter.

Listing 14.2 PARSESTR.FRM--Using the InStr Function to Divide a String into Words

Sub PrintWords(stInput As String)
    Dim inCounter As Integer
    Dim inFoundPos As Integer
    
    Const PARSECHAR = " " `Space
    
    `If string is blank then do nothing
    If Len(stInput) = 0 Then Exit Sub
    
    `Start at the first character
    inCounter = 1
    
    `Search for a space
    inFoundPos = InStr(inCounter, stInput, PARSECHAR)
    
    `If a space is found print the word and keep searching
    While inFoundPos <> 0
      Debug.Print Mid$(stInput, inCounter, inFoundPos - inCounter)
      inCounter = inFoundPos + 1
      inFoundPos = InStr(inCounter, stInput, PARSECHAR)
    Wend
    
    `Print the remainder of the string
    If inCounter < Len(stInput) Then
        Debug.Print Mid$(stInput, inCounter)
    End If    
End Sub

The input and results of this code appear in Figure 14.9.

FIG. 14.9
Use InStr to find all the spaces in a string.

Determining the Length of the String For many operations, you may need to know how many characters are in a string. You might need this information to know whether the string with which you are working will fit in a fixed-length database field. Or, if you are working with big strings, you may want to make sure that the combined size of the two strings does not exceed the capacity of the string variable. In any case, to determine the length of any string, the Len function is used, as illustrated in the following code line:

result = Len(inputstr)

You can use the Len function in a number of applications. In many cases, it is used to deter-mine whether there are any characters in a string. If there are no characters, you may want to issue an error message, or at least bypass any further processing. In Listing 14.1, you saw how the Len function was used to find the number of characters so that you could use the Right function to get the remainder of a string.


CAUTION: The Len function reports only the number of characters that are present in a string. It does not report whether a string will fit within a control or on a line of a printout. For these purposes, you need to use the TextWidth and TextHeight methods of the object to which the string is being written. These methods are discussed in Chapter 16, "Displaying and Printing Reports."

See "Using TextHeight and TextWidth," Chapter 15

Getting Rid of Spaces Long strings typically contain spaces in the middle of the string, which are necessary for proper spacing of words, paragraphs, and so on. However, you also may end up with spaces at the beginning or end of your strings, which often are unwanted spaces. These spaces typically occur when the user accidentally types a space at the beginning or end of a text field. They also show up when you are using a fixed-length string and the number of characters in the string do not fill the available space. For example, the following calls to the Len() function would each return a different number:

Print Len("Hello, world!")
Print Len("   Hello, world!")
Print Len("Hello, world!   ")

Most of the time, spaces don't do any harm except take up a little memory. However, when you combine strings, or try to take action based on their content, unwanted spaces can cause all kinds of problems. For example, suppose you had two 30-character text boxes for first and last names. The user could inadvertently type three characters of text and then a bunch of spaces. If you needed to concatenate the first and last name for a mailing label, the extra spaces would be included. However, Visual Basic provides some string "trimming" functions to eliminate the trailing spaces.

To get rid of the spaces at the end of a string, you can use one of these Visual Basic functions:

Each of these functions use a similar syntax. The code in the following lines shows how the Trim function would be used to remove the spaces in the mailing label example (the results of these trimmed strings are shown in Figure 14.10):

picMail.Print Trim(FirstName) & " " & Trim(LastName)
picMail.Print Trim(Address)
picMail.Print Trim(City) & ", " & Trim(State) & "  " & Trim(Zip)

FIG. 14.10
This user typed extraneous spaces (that we can't see) after the words "Joe" and "Smallville," but Visual Basic's Trim function removed them.

Extracting Pieces of a String Okay, you have the capitalization of the string right and you have removed all the spaces that you don't need at the ends of the string, but now you find you need to work with only a part of the string. Can Visual Basic help with this problem too? Of course it can. You will find many situations in which you need to work with only part of a string. Perhaps you'll need to extract the first name of a person from her full name, or maybe you'll need to make sure that the information with which you are working will fit in the database field in which it needs to be stored. This is easy to accomplish by using one of the following Visual Basic functions:

First, look at the Left and Right functions, as these are slightly easier to use. (By the way, none of these functions is hard to use.) To use these functions, you specify the input string and the number of characters to be retrieved. The syntax of these two statements is shown in the following lines:

OutStr = Left(InptStr, NumChars)
OutStr = Right(InptStr, NumChars)

When you use these functions, the number of characters specified must be a number greater than or equal to 0. If you enter 0, a 0 length string is returned. If the number of characters is greater than the length of the input string, the entire string is returned. You will find, as you write programs that manipulate strings, that the Left and Right functions are often used in conjunction with the other string functions.

This is illustrated in Listing 14.3, which retrieves the first name of a person from the full ame. This function is used to print name tags for an organization's events. Figure 14.11 shows how this code is used. The function assumes that the person's first and last names will be separated by a space. The function then looks for a space in the input text and, upon finding the space, it extracts the characters preceding the space and supplies those characters as the first name. If there are not any spaces in the input string, the function assumes that only a first name was entered.

Listing 14.3 AMETAG.FRM--Using the InStr and Left Functions to Extract a Person's First Name

BasString = Trim(txtName.Text)
I = InStr(BasString, " ")
If I > 0 Then
    ScndString = Trim(Left(BasString, I))
Else
    ScndString = BasString
End If
PrtLine1 = ScndString
PrtLine2 = BasString

FIG. 14.11
Print name tags using the Left and InStr functions.

Mid is another function that is used to retrieve a substring from a string, and it works in a similar manner to the Left and Right functions, but it has one additional argument. The Mid function is used to retrieve a letter, word, or phrase from the middle of a string.

The Mid function contains two required arguments and one optional argument, as shown in the following syntax:

newstr = Mid(sourcestr, startpos[, numchars])

Startpos represents the character position at which the retrieved string will begin. If startpos is greater than the length of the string, an empty string is returned. The optional argument numchars represents the number of characters that will be returned from the sourcestr. If numchars is omitted, the function will return all characters in the source string, from the starting position, on to the end. The following are some examples of the Mid function:

Print Mid("Robert Allen",8)   `Returns "Allen"
Print Mid("Robert Allen",8,2) `Returns "Al"

Replacing Characters in a String ow to add a little confusion to your life. You just saw how the Mid function retrieves a piece of a string from the middle of a source string. The same keyword, Mid, is used to replace a part of a string. However, the syntax is quite different, in that we're using the function on the left-hand side of an assignment statement in this case. When used to replace characters in a string, it is referred to as the Mid statement. The Mid statement replaces part of one string with another string by using the following syntax:

Mid(sourcestr, startpos[, numchars]) = replstr

The sourcestr in this case is the string that will receive the replacement characters. Sourcestr must be a string variable; it cannot be a literal string or string function. Startpos is the character position at which the replacement will start. This must be an integer number greater than zero. Numchars is an optional argument that specifies the number of characters from the replacement string being used by the function. Replstr represents the string containing the replacement characters. This string can be a string variable, a literal string, or a string function.

The Mid statement preserves the original length of the string. In other words, if the space remaining between the starting position and the end of the string is less than the length of the replacement string, only the leftmost characters will be used from the replacement string.

There are a number of uses for the Mid statement in your programs. Remember the capitali-zation example in Listing 14.1? Using the Mid statement, you can perform the same function with the following code:

inptstr = Trim(txtInput.Text)
frstLtr = UCase(Left(inptstr,1))
Mid(inptstr, 1) = frstLtr
txtOutput.Text = inptstr

In another program, I needed to eliminate any carriage return or line feed characters that were embedded in a string to keep them from causing printing problems. I used the Mid statement to replace these characters with a space. This is shown in Listing 14.4.

Listing 14.4 AMETAG.FRM--Using the Mid Statement to Eliminate Specific Characters in a String

`Replace Line feeds with spaces
   FindPos = 0
    Do
     FindPos = InStr(sInput, Chr$(10))
      If nFindPos > 0 Then Mid(sInput, nFindPos) = " "
    Loop Until nFindPos = 0
`Replace Carriage returns with spaces
   FindPos = 0
    Do
     FindPos = InStr(sInput, Chr$(13))
      If nFindPos > 0 Then Mid(sInput, nFindPos) = " "
    Loop Until nFindPos = 0

Working with Specific Characters

Listing 14.4 shows the use of a function that you have not seen before--the Chr function. This function is used to return a character that corresponds to a specific ASCII code. For example, the following two statements both print "HELLO":

Print "HELLO"
Print Chr$(65) & Chr$(69) & Chr$(76) & Chr$(76) & chr$(79)


NOTE: As with other functions mentioned earlier in this chapter, Chr has two forms: Chr() returns a Variant; Chr$() returns a string.

In the previous example, typing HELLO is a lot simpler. However, there are some characters you can't type, like line feeds and carriage returns, so you have to use the Chr function:

Print "Line 1" & Chr$(13) & Chr$(10) & "Line 2"

The Carriage return/line feed combination deserves special mention. Frequently, you will find yourself using this combination to force a new line in a string, text box, or message box. For this purpose, Visual Basic has included an intrinsic constant, vbCrlf, so that the preceding line of code could be rewritten as follows:

Print "Line 1" & vbCrLf & "Line 2"

The Chr function can also be used to include quotes:

Print Chr$(34) & "This will be printed with quotes" & Chr$(34)
Print "this will not have quotes"

You can also use the Chr function to return any letter or number character. Table 14.3 lists some commonly used ASCII character codes.

Table 14.3 ASCII Codes for Some Commonly Used Characters

Code Represents
8 BackSpace
9 Tab
10 Line feed
13 Carriage Return
32 Space
34 Double quote (")
48 0 (the character for zero)
65 A
97 a

Asc is the companion function to the Chr function. Asc returns the ASCII code of the input character. The following code shows how Asc is used:

Print Asc("A") `Returns 65

Working with Strings and Numbers

Another thing to consider is the relationship between strings and numbers. You may already know that some numbers are often treated as character strings. ZIP codes and phone numbers are two such examples. However, there are times when you need to convert a number to a string variable to use it in a string function, or to print it in combination with another string. Likewise, there are times when you need to use numbers contained in a string variable in a mathematical equation or a numeric function.

Visual Basic provides the Str function to convert a number to a string, and the Val function to convert a string to a number. To convert a number to a string, you can do the following:

numstr = Str(inptnum)

numstr represents a string variable that contains the output of the function. inptnum represents the number to be converted. This can be a number, a numeric variable, or a numeric function. If inptnum is a positive number, Str will return a space in front of the number because Str reserves one character to contain a negative sign, if necessary.

To convert a string to a number, the Val function is used, as follows:

numvar = Val(inptstr)

numvar represents a numeric variable that stores the output of the function. inptstr can be a literal string, a string variable, or a string function. The Val function first strips out any spaces from the string and then starts reading the numbers in the string. If the first character in the string is not a number (or minus sign), Val returns 0. Otherwise, Val reads the string until it encounters a non-numeric character. At this point, it stops reading and converts the digits it has read into a number.

A Closing Note on Working with Strings

In the preceding few sections, you have read a lot of information about string functions. Make sure, before continuing, that you have learned the concept of what each function is doing. More importantly, understand that string functions return values, but they do not modify the input. Consider the following example with the UCase function:

Dim s1 As String
Dim s2 As String
s1 = "which case am i"
s2 = UCase$(s1)

After this code is executed, the variable s2 will appear in all uppercase letters, whereas s1 will remain unchanged.

Also note that it is common practice to nest string functions within statements rather than using an extra variable. For example, consider the following Select Case statement, which uses a bunch of nested string functions to help with input validation. Users can come up with any capitalization they want to, but it will be handled by the code.

stUserInput = InputBox$("Type Yes or No, please!")
Select Case Left$(Trim$(Ucase$(stUserInput)),1)
   Case "Y"
     MsgBox "Yes"
   Case "N"
     MsgBox "No"
   Case Else
     MsgBox "type YES or NO please!"
End Select

Controlling the Appearance of Your Text

Being able to manipulate the text in a string is only part of working with text. After manipulating the text within your program, you probably will also want the capacity to control how the text appears to the user. This is the function of fonts. If you have worked with a word processor at all, you probably have done some work with fonts. A font describes how the letters and numbers that you use will look. Figure 14.12 shows several different fonts in different sizes. Fonts are like different styles of handwriting--some people print in block capital letters, other people write in script, and some people produce beautiful calligraphy.

FIG. 14.12
Fonts control the appearance of the text on-screen.

Properties of the Font Object

You may remember from earlier chapters that the Font property is actually an object that has its own properties. The following font object properties control the appearance of the fonts in your program:

Recall that the Font property can be accessed in code with dot notation:

TxtName.Font.Name="Arial"
TxtName.Font.Size = 10

The Font property that you probably will use most often is the Size property. Typically, the default font size is in the range of 8 to 12 points. If desired, though, you can set the font size anywhere from 1 to over 2,000 points, though I wouldn't recommend either extreme. A point size below 8 becomes difficult to read, and a point size of 250 will cause just a few characters to fill the entire screen. Figure 14.13 gives you an idea of the different point sizes.

FIG. 14.13
Fonts can range in size from tiny to jumbo.


NOTE: A point defines the height of the character cell used to draw a character. It is equivalent to 1/72 of an inch. Therefore, when using a 12-point font, approximately six lines of text fit in a vertical inch.

The idea behind using different fonts and font attributes is to increase the readability of the information on the screen or to add emphasis to a particular piece of information. The proper use of fonts can greatly enhance the programs you create.


CAUTION: It is easy to get carried away using different fonts, and this can cause some problems. Too many different fonts on a single screen can make it look disorganized and confusing. It is best to choose one or two fonts and then use the fonts' attributes to achieve effects. This will give your programs a cleaner look. However, try not to get carried away with the other attributes!


Making Life Easier for Portable Computer Users

One big advantage of being able to control font size is that you can make text more readable on portable computers by increasing the font size. Portable (laptop) PC users probably already know this well. The 10- or 12-point font that looks great on a 17-inch desktop monitor can be difficult to read on the 10-inch screen of a portable computer. Therefore, keep in mind the users' screen resolution. While developers and other "techies" might have 1024x768 or higher screen resolution, the general public usually uses a much lower resolution, such as 800x600, or even 640x480.


As you may have noticed already, to set a particular font, you have to know its name. It's important to account for the fact that not all systems have the same fonts installed. The Screen and Printer objects have properties that let you determine the available fonts for display and printing, as demonstrated in the following code:

  Dim inCount As Integer
  For inCount = 0 To Screen.FontCount - 1
    Print Screen.Fonts(inCount)
 Next inCount

Of course, you also could use a Font dialog box (from the Common Dialog control) to let the user select from a list of available fonts.

See "Form Properties Revisited," Chapter 4

See "The Font Dialog Box," Chapter 5

Controlling Fonts in Your Program

Visual Basic lets you control all the attributes of the fonts in your programs. You can specify a font for an entire form or for individual controls. You can even control the fonts used by the printer. Visual Basic enables you to set up fonts during the design phase of your program. It also gives you the ability to actually change them while the program is running. This means that you can allow your user to select fonts for certain parts of the program. Or, you can set up the program so that the fonts change in response to some event in the program, such as a change in the value of a text box.

Setting an Initial Font The default font for Visual Basic programs is called MS Sans Serif. This is the font used in the title bars of most Windows programs. Unless you change the font for a control, this font will be used in every control that you add to your program. If you want to use a single font for all the components on a form, you can set that font as the form's base font before you place any controls on the form. When you change a form's font before adding any controls, all its controls will use that same font (assuming you don't change it for any subsequent controls).

To set the base font for your form, click the form, and then open the Properties window by pressing F4 or clicking the Properties Window button. Click the ellipsis button next to the Font property to open the Font dialog box. This dialog box, shown in Figure 14.14, enables you to choose the base font, as well as any other attributes you want to set for the form's Font object. Once you have set a particular font, it will be used for all controls added to the form.


NOTE: Changing the font used for the form will not affect any controls already on the form, only new controls that are added to the form. Also, the font setting does not affect the font used for the form's caption (the text in the title bar). This font is controlled from the Windows Control Panel setting.

FIG. 14.14
You can change the font for a form by using the Font dialog box.


CAUTION: If you are creating programs for others to use on their machines, be careful choosing fonts. Others using your program may not have the same fonts as you do. Windows will attempt to substitute a similar font on the user's machine, but the resulting display may be unacceptable.

Setting the Font for Individual Controls In addition to setting the font for the form, you may want to set a different font, or different attributes, for a single control or group of controls. For example, you may want to give all of your labels one font and all your text boxes a different font. Or, you may decide to use one font for controls containing numbers and another font for those containing letters. (For more information about working with multiple controls, see Chapter 4, "Working with Forms and Controls.")

See "Working with Multiple Controls in the Design Environment," Chapter 4

Fonts for individual controls can be changed the same way they are changed for the form. This is done in the design environment by using the Font dialog box. Each control has a Font property. In fact, you could use a different font for each control on your form, though this would lead to a very confusing form.

Changing Fonts While the Program Is Running Changing fonts in the design environment is great, but if you want your users to be able to set the fonts in your program, you have to provide a way to change your fonts in code. Fortunately, this is easy to do with assignment statements. Each of the properties of the font object can be set from code, as well as from the design environment. Take a brief look at how each property is handled in code; Figure 14.15 shows a program that illustrates the different font properties.

FIG. 14.15
Fonts can be controlled from code.

Changing the Base Font To change the base font of an object, you use an assignment statement that specifies the Name property of the object's Font property. While you can specify the name of a font in a variable or constant, typically you will use the Font dialog box of the CommonDialog control to ask the user for the desired base font. This makes it easy for your users to choose a font. (For more information about the Font dialog box, see Chapter 6, "Using Dialogs to Get Information.")

See "The Font Dialog Box," Chapter 6

The following line of code shows how you would change the base font of an object:

txtFontDemo.Font.Name = "Times New Roman"

Changing the Size of a Font To set the size of a font, you specify an integer value for the Size property of the Font object. As stated earlier, this value can range from 1 to over 2,000, although values of 8 to 48 are the ones most often used. The following line shows how a font's size is set:

txtFontDemo.Font.Size = 16


CAUTION: When changing the font size in code, the control using the font may not be able to adjust to accommodate the new size. Therefore, part of the text in the control may not be visible to the user.

Recall from earlier chapters that setting Font properties of a text box causes all existing text to change, whereas setting Font properties of a form or printer does not.

Setting the Other Properties of the Font Object The other four key properties of the Font object (Bold, Italic, Underline, and StrikeThrough) all have possible values of either True or False. To turn on a property, set its value to True; to turn off a property, set its value to False. The following lines of code illustrate this:

txtFontDemo.Font.Bold = True
txtFontDemo.Font.Italic = True
txtFontDemo.Font.StrikeThrough = True
txtFontDemo.Font.Underline = True

Working with Formatted Text

Thus far, you have learned how the user can enter text and how you can display text by using the TextBox and Label controls. You also have learned how to manipulate text in your program. Finally, you have seen how fonts can be used to change the appearance of text. But, even with all these capabilities, you haven't learned how to give your users the capability to format text like they can do with a word processor.

Starting with version 4, Visual Basic includes the RichTextBox control. This control enables the user to apply different fonts, font attributes, and colors to different sections of the text being edited. The user can also control the justification of text and create such effects as indention and bulleted lists. The RichTextBox control accomplishes all these functions by providing support for the Rich Text Format (RTF) language. The control interprets RTF codes and applies the proper formatting to the text. The control also has the capability of importing and exporting RTF files. Figure 14.16 shows how text appears in a RichTextBox control and which RTF codes are used to create the effects.

FIG. 14.16
RTF codes allow formatting information to be stored in a text file.


NOTE: The RichTextBox control is also discussed in Chapter 15, "Displaying and Printing Reports."

See "Using the RichTextBox Control," Chapter 15


RTF versus HTML
You might think that because both RTF and HTML use codes to store formatting information in a text file, they can be used together, or interchangeably.

Unfortunately, that is not true. RTF codes originally were designed as a means for different word processors to exchange information through the use of text files. This means that you can work in one word processor, save the information to an RTF file, and then send the information to another person with a different word processor. The other person can then see the formatting of the text when the file is opened. HTML, on the other hand, is designed to pass formatting information across the Internet so that it can be interpreted and displayed by a browser. While both formats use the same concept of tags to embed formatting information, the tags used are not the same.


Using the RichTextBox Control

In many ways, the RichTextBox control works the same way as the standard text box. It shares many properties with the TextBox control, including the Text property, which works in the same way. In fact, the rich text box supports all properties that are supported by the text box. This makes it easy to substitute rich text boxes for any text boxes in your program. Simply delete a text box and insert a rich text box with the same name in its place. You do not need to change any of your program code to accomplish this. You will, however, want to add new code to take advantage of the additional capabilities of the rich text box.

Like the TextBox control, the RichTextBox control supports single- and multiple-line display and editing of text. Both controls can be locked (by setting the Locked property to True) to provide a read-only display of information. Both controls support cut, copy, and paste operations for editing. And finally, both can be bound to a Data control for use in database applications.

The discussion in this section focuses on the unique capabilities of the RichTextBox control. To learn about the basic capabilities that it shares with the text box, refer to the section "Getting and Displaying Text," earlier in this chapter.

Understanding Text Formatting The RichTextBox control enables the user to select a portion of the text in the control and apply special formatting to it. The user can change the font of the selection, make the selection bold or italic, or underline the selection. When the user applies any or all of these formats to the selection, the new formatting is shown on-screen. In addition, formatting codes (which are not shown on the screen) are placed in the text of the control. These codes allow the formatting information to be stored and then used by other programs that support RTF format codes. This means that you can export your formatted text to a word processor or other program and retain the formatting.

Setting Up the RichTextBox Control The RichTextBox control is one of the custom controls that comes with Visual Basic. You must add it to the Toolbox by using the Components dialog box, which is accessible by choosing the Components item from the Project menu. Once you have added the control to the Toolbox, you can use it just like any other control. Simply select it from the Toolbox and draw it on your form. As you can see in Figure 14.17, a rich text box looks just like a standard text box on the form. But remember--looks can be deceiving.

FIG. 14.17
The RichTextBox control looks like a standard text box when drawn on the form.

Working with the Font Options

The rich text box is a very powerful tool for creating programs that edit text because it provides tremendous control over the formatting of the text it contains. This section will cover many of the effects that are possible with the rich text box.

A common denominator of all the formatting options is the manner in which they affect the text that is displayed in the control. If you set a format property while some text is selected, only the selected text is affected by the new property value. However, if you set a new format value with no text selected, the property affects all text typed from the point at which it is inserted, until the property value is again changed. This works exactly like the formatting options in a word processing program.

Setting the Initial Font After placing a rich text box on your form, probably the first thing you will want to do is set the properties of the Font object. You do this by following the guidelines described earlier in this chapter in the section "Controlling Fonts in Your Program." Setting the font in the design environment does two things--it sets the initial font the user sees and it sets the initial values of the SelFontName, SelFontSize, SelBold, SelItalic, SelUnderline, and SelStrikeThru properties. These properties control the appearance of selected text.


NOTE: If you change the value of the Font property or any of its attributes, it will affect all text that has not had any special formatting applied.

In a similar manner, setting the ForeColor property of the RichTextBox control sets the initial value of the SelColor property.

Changing the Appearance of Words After the font has been set and the user begins entering text, formatting individual words and phrases can be accomplished by setting one or more of the following properties:

Each of these properties can be set by using an assignment statement. Some of these properties can be applied through the use of buttons in a toolbar that will set the properties. Figure 14.18 shows the main form of an example project. This project contains a RichTextBox control and a toolbar that enables the user to turn on the SelBold, SelItalic, SelUnderline, and SelStrikethru properties of the selected text. The form also contains drop-down lists that enable users to change the font and font size of the selection.

See "Creating a Toolbar for Your Application," Chapter 5

Figure 14.19 shows the form after modifying the font for portions of the text.

FIG. 14.18
You can set the font properties of text by using a toolbar and the proper code.

FIG. 14.19
You can change the appearance of a single word or a phrase with the RichTextBox control.

Working with Paragraphs

With the RichTextBox control, you also can change the alignment of individual paragraphs in your text. You can align paragraphs along the left edge of the RichTextBox (the default), or along the right edge, or centered in the box. The SelAlignment property controls the alignment of the paragraph and can have one of three values, which are set forth in Table 14.4. Figure 14.20 shows three RichTextBox controls that contain the same paragraph but with different alignment settings.

FIG. 14.20
Setting the SelAlignment property controls how the selected paragraphs appear in the control.

Table 14.4 The SelAlignment Property Values and Their Effects

Property Value Effect
rtfLeft (0) Sets the beginning of each line flush with the left side of the box.
rtfRight (1) Sets the end of each line flush with the right side of the box.
rtfCenter (2) Centers each line between the edges of the box.

Searching the Text

Another feature of the RichTextBox control is that you can search its contents for a string of text. You can choose to have the search confined to the selected text or to a specific section of the text. You can also have the search look through the entire contents of the rich text box.

Another available search option is the choice of whether to match the case of the search string. If case matching is not required, the strings "The" and "the" are considered a match. If case matching is required, the strings do not match because one contains a capital letter and the other does not.

This sounds very similar to the Instr function; as a matter of fact, you could use the Instr function with the RichTextBox control's Text property. However, the RichTextBox control has a special function of its own: the Find Method. This method specifies the string for which to search, the starting and ending points of the search, and any optional parameters. An advantage to using this instead of Instr is that Find causes the text it finds to be selected, so that font properties can be applied. The Find method uses the following syntax:

rtbname.Find(searchstr, start, end, options)

In this method, the searchstr parameter identifies the string that you want to find. This can be a literal string, a variable, or a string function. Start and end specify the scope of the search. If both parameters are included, the search is performed on all text between the two points. If end is omitted, the entire contents of the RichTextBox are searched. If both parameters are omitted, only the selected text is searched.

Adding a Splash of Color

Using different fonts is one way to change the appearance of information in your programs. Another method is to use color, which can grab a user's attention, convey important information, or simply make an application more visually appealing.

Setting the Color of Controls at Design Time

As with fonts, you can set color properties for your form and for individual controls at design time. In fact, most controls allow you to set two colors. You can set the background color by using the BackColor property and you can set the foreground or text color by using the ForeColor property.


NOTE: Unlike font settings, the color settings for a form do not carry forward to controls placed on the form.

The default setting for each of the color properties is based on the Windows system color settings. The default setting of the BackColor property is the window background color, usually white. The default setting of the ForeColor property is the color of the text in Windows menus, usually black.


NOTE: If you use the default color settings, changing the Windows system colors will make the colors in your program change too. This is an important point to consider when distributing programs.

There are two ways to set the colors of your form and controls at design time. You can either use the color palette or select colors from a list from the Properties window. You can also, of course, set color properties by using code.

Using the Color Palette The color palette is one of the tools available to you at design time. The color palette is accessed by choosing Color Palette from the View menu. The color palette is shown in Figure 14.21.

FIG. 14.21
The color palette enables you to easily choose the foreground and background colors of your controls.

The color palette consists of a property selection area (two concentric squares), a series of color indicators, and two command buttons. To change the color properties of one of your controls, first select the control with a single-click. Then, using the mouse, choose either the foreground (click the inner box) or background (click the outer box). Next, click the color that you want in the color indicator boxes. As you choose the colors, you immediately will see the results both in the color palette and in your control. If you want to return your control's colors to their default values, just click the default button.

Using the Color List The other way to set the colors of a control at design time is to modify the individual properties from the Properties window. To set a color, select the property (ForeColor, BackColor, or one of the other color properties); then click the arrow button at the right of the property value. This opens the color list (see Figure 14.22). This color list contains two tabs. The first tab shows the system colors for Window Text, Desktop, Window Background, and so on. You can choose to use one of these colors by clicking the appropriate color block. The other tab contains a series of color squares from the color palette. On this tab, you can choose the color you want by clicking the appropriate square.

FIG. 14.22
You can set the color of the ForeColor or BackColor property from the color list.

Changing Colors with Code

As with most everything else, the ForeColor and BackColor properties can be changed with code in your program. You do with an assignment statement in which you tell the program what control and property to change, and what the new value is for the property. But what are the values? Can you just say, "Make this red?" Well, almost.

In the computer world, every color is a combination of some amount of red, green, and blue; the color number used as the property setting represents the amounts of blue, green, and red, respectively, in the desired color. The number is often represented in hexadecimal format; for example, blue is represented by &H00FF0000&.

If you are a glutton for punishment, you can figure out how much red, green, and blue go into a particular shade and then convert that information into the right numerical value. Fortunately, it is much easier than that. Visual Basic provides a set of constants for several common colors. These constants represent the numerical value needed for the color. Table 14.5 shows the names of the constants and the color they represent.

Table 14.5 Color Constants Provide the Numerical Values for Many Common Colors

Color Constant Numerical Value (Decimal)
Black vbBlack 0
Red vbRed 255
Green vbGreen 65280
Yellow vbYellow 65535
Blue vbBlue 16711680
Magenta vbMagenta 16711935
Cyan vbCyan 16776960
White vbWhite 16777215

To use one of these color constants, simply enter its name in the assignment statement. The following code displays yellow text on a blue background:

ColorDemo.ForeColor = vbYellow
ColorDemo.BackColor = vbBlue

In addition to the predefined color constants, you can use Visual Basic's RGB function, which accepts parameters for the amounts of red, green, and blue (each expressed in the range of 0-255) and returns the appropriate color number. For example,

frmTestForm.BackColor = RGB(0, 255, 0) 

sets a form's background color to green.


TIP: If you want to use a color that does not have a constant, the Common Dialog control's Color dialog box can be used to find out the numeric value.

Remember, the colors you select may be affected by the color scheme on an individual PC. This means selecting colors that change with the system will make your application better suited for an individual's color preferences. On the other hand, it is not unusual for the user to "mess up" his color scheme. For example, he might pick the right color combination so that highlighted text looks the same as other text. Therefore, in some instances, it might be beneficial for a program to choose a specific color. The determining factor should be how important colors are to the usefulness of your program.

From Here...

In this chapter, you learned about manipulating text--both from code and in the design environment. You saw how the Masked Edit control can make input validation easier, and how the RichTextBox control can be the foundation of a simple word processor. The code examples in the chapter also provided some examples of what you can do with string functions. Finally, some additional properties of the font object were introduced and you learned how to set colors in an application.


Previous chapterNext chapterContents


Macmillan Computer Publishing USA

© Copyright, Macmillan Computer Publishing. All rights reserved.