[Page 60 (continued)]3.2. Visual Basic Events When a Visual Basic program runs, the form and its controls appear on the screen. Normally, nothing happens until the user takes an action, such as clicking a control or pressing a key. We call such an action an event. The programmer writes code that reacts to an event by performing some functionality. The three steps in creating a Visual Basic program are as follows: 1. | Create the interface; that is, generate, position, and size the objects.
| 2. | Set properties; that is, configure the appearance of the objects.
| 3. | Write the code that executes when events occur.
| Section 3.1 covered Steps 1 and 2; this section is devoted to Step 3. Code consists of statements that carry out tasks. In this section, we limit ourselves to statements that change properties of a control or the form while a program is running. Properties of controls are changed in code with statements of the form controlName.property = setting where controlName is the name of the control, property is one of the properties of the control, and setting is a valid setting for that property. Such statements are called assignment statements. They assign values to properties. Three examples of assignment statements are as follows: [Page 61]The statement txtBox.Text = "Hello" displays the word Hello in the text box. The statement btnButton.Visible = True makes the button visible. The statement txtBox.ForeColor = Color.Red sets the color of the characters in the text box named txtBox to red. Most events are associated with controls. The event "click on btnButton" is different from the event "click on lstBox." These two events are specified btnButton.Click and lstBox.Click. The statements to be executed when an event occurs are written in a block of code called an event procedure. The first line of an event procedure (called the header) has the form Private Sub objectName_event(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles objectName.event Since we do not make any use of the lengthy text inside the parentheses in this book, for the sake of readability we replace it with an ellipsis. However, it will automatically appear in our programs each time Visual Basic creates the header for an event procedure. The structure of an event procedure is Private Sub objectName_event(...) Handles objectName.event statements End Sub where the three dots (that is, the ellipsis) represent ByVal sender As System.Object, ByVal e As System.EventArgs Words such as "Private," "ByVal," "As," "Sub," "Handles," and "End" have special meanings in Visual Basic and are referred to as keywords or reserved words. The Visual Basic editor automatically capitalizes the first letter of a keyword and displays the word in blue. The word "Sub" in the first line signals the beginning of the procedure, and the first line identifies the object and the event occurring to that object. The last line signals the termination of the event procedure. The statements to be executed appear between these two lines. (Note: The word "Private" indicates that the event procedure cannot be invoked by another form. This will not concern us until much later in the book. The expression following Handles identifies the object and the event happening to that object. The expression "objectName_event" is the default name of the procedure and can be changed if desired. In this book, we always use the default name. The word "Sub" is an abbreviation of Subroutine.) For instance, the event procedure [Page 62]Private Sub btnButton_Click(...) Handles btnButton.Click txtBox.ForeColor = Color.Red End Sub changes the color of the words in the text box to red when the button is clicked. An Event Procedure Walkthrough The form in Figure 3.12, which contains two text boxes and a button, will be used to demonstrate what event procedures are and how they are created. Three event procedures will be used to alter the appearance of a phrase appearing in the text box. The event procedures are named txtFirst_TextChanged, btnRed_Click, and txtFirst_Leave. Figure 3.12. The interface for the event procedure walkthrough. Object | Property | Setting |
---|
frmDemo | Text | Demonstration | txtFirst | | | txtSecond | | | btnRed | Text | Change Color to Red |
1. | Create the interface in Figure 3.12 in the Form Designer. The Name properties of the form, text boxes, and button should be set as shown in the Object column. The Text property of the form should be set to Demonstration, the Text property of the text boxes should remain blank, and the Text property of the button should be set to Change Color to Red.
| | | 2. | Click the right mouse button anywhere on the Main area, and select View code. The Form Designer is replaced by the Code window (also known as the Code view or the Code editor). See Figure 3.13.
Figure 3.13. The Code window. [Page 63]The page tab, labeled frmDemo.vb, corresponds to the Code window. You press the page tab labeled frmDemo.vb [Design], when you want to return to the Form Designer window. Just below the title bar are two drop-down list boxes. The left box is called the Class Name box, and the right box is called the Method Name box. (When you hover the mouse pointer over one of these list boxes, its type appears in a tooltip.) We will place our program code between the two lines shown. Let's refer to this region as the program region.
| 3. | Click on the tab labeled "frmDemo.vb [Design]" to return to the Form Designer.
| 4. | Double-click on the first text box. The Code window reappears, but now the following two lines of code have been added to the program region and the cursor is located on the line between them.
Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged End Sub The first line is the header for the event procedure named txtFirst_TextChanged. This procedure is triggered by the event txtFirst.TextChanged. That is, whenever there is a change in the text displayed in the text box txtFirst, the code between the two lines just shown will be executed.
| 5. | Type the line
txtFirst.ForeColor = Color.Blue at the cursor location. When you type the first period, a list containing all the properties of text boxes appears. See Figure 3.14(a). (Each property is preceded by a little Properties window icon. The list also contains something called methods, which we will discuss later.) At this point, you can scroll down the list and double-click on ForeColor to automatically enter that property. Or, you can keep typing. After you have typed "For," the list appears as in Figure 3.14(b). At that point, you can press the Tab key to enter the highlighted word "ForeColor." This feature, known as Member Listing, is one of the helpful features of Visual Basic that use a Microsoft technology called IntelliSense.
Figure 3.14. IntelliSense at work. | | [Page 64] | 6. | Return to the Form Designer and double-click on the button. The Code window reappears, and the first and last lines of the event procedure btnRed_Click appear in the program region. Type the line that sets the ForeColor property of txtFirst to Red. The event procedure will now appear as follows:
Private Sub btnRed_Click(...) Handles btnRed.Click txtFirst.ForeColor = Color.Red End Sub | 7. | Click on the down-arrow button to the right of the Class Name box and on txtFirst in the drop-down list.
| 8. | Click on the down-arrow button to the right of the Method Name box and on Leave in the drop-down list box. (The event txtFirst.Leave is triggered when the focus is removed from the text box.) The first and last lines of the event procedure txtFirst_Leave will be displayed. In this procedure, type the line that sets the ForeColor property of txtFirst to Black. The Code window will now look as follows:
Public Class frmDemo Private Sub txtFirst_Leave(...) Handles txtFirst.Leave txtFirst.ForeColor = Color.Black End Sub Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged txtFirst.ForeColor = Color.Blue End Sub Private Sub btnRed_Click(...) Handles btnRed.Click txtFirst.ForeColor = Color.Red End Sub End Class | 9. | Place the cursor on the word "ForeColor" and press F1. Visual Basic now displays information about the foreground color property. This illustrates another help feature of Visual Basic known as context-sensitive help.
| 10. | Now run the program by pressing F5.
| 11. | Type something into the text box. In Figure 3.15, the blue word "Hello" has been typed. (Recall that a text box has the focus whenever it is ready to accept typingthat is, whenever it contains a blinking cursor.)
Figure 3.15. Text box containing input. | | [Page 65] | 12. | Click on the second text box. The contents of the first text box will become black. When the second text box was clicked, the first text box lost the focus; that is, the event Leave happened to txtFirst. Thus, the event procedure txtFirst_Leave was invoked, and the code inside the procedure was executed.
| 13. | Click on the button. This invokes the event procedure btnRed_Click, which changes the color of the words in txtFirst to Red.
| 14. | Click on the first text box, and type the word "Friend" after the word "Hello." As soon as typing begins, the text in the text box is changed and the TextChanged event is triggered. This event causes the color of the contents of the text box to become blue.
| 15. | You can repeat Steps 11 through 14 as many times as you like. When you are finished, end the program Alt+F4 by pressing clicking the End icon on the Toolbar, or clicking the Close button (X) on the form.
| Properties and Event Procedures of the Form You can assign properties to the Form itself in code. However, a statement such as frmDemo.Text = "Demonstration" will not work. The form is referred to by the keyword Me. Therefore, the proper statement is Me.Text = "Demonstration" To display a list of the events associated with frmDemo, select "(frmDemo Events)" from the Class Name box and then open the Method Name box. The Header of an Event Procedure As mentioned earlier, in a header for an event procedure such as Private Sub btnOne_Click(...) Handles btnOne.Click btnOne_Click is the name of the event procedure, and btnOne.Click identifies the event that triggers the procedure. The name can be changed at will. For instance, the header can be changed to Private Sub ButtonPushed(...) Handles btnOne.Click Also, an event procedure can be triggered by more than one event. For instance, if the previous line is changed to Private Sub ButtonPushed(...) Handles btnOne.Click, btnTwo.Click the event will be triggered if either btnOne or btnTwo is clicked. We have been using ellipses (...) as place holders for the phrase ByVal sender As System.Object, ByVal e As System.EventArgs [Page 66]In Chapter 4, we will gain a better understanding of this type of phrase. Essentially, the word "sender" carries a reference to the object that triggered the event, and the letter "e" carries some additional information that the sending object wants to communicate. We will not make use of either "sender" or "e". Comments The Visual Basic editor automatically indents the statements inside procedures. In this book, we indent by two spaces. To instruct your editor to indent by two spaces, select Options from the Tools menu, and uncheck the "Show all settings" box in the Options window that appears. Expand "Text Editor Basic" or "Text Editor," click on "Editor," enter 2 into the "Indent size:" box, and click on OK. The event control.Leave is triggered when the specified control loses the focus. Its counterpart is the event control.Enter which is triggered when the specified control gets the focus. A related statement is control.Focus() which moves the focus to the specified control. We have ended our programs by clicking the End icon or pressing Alt + F4 more elegant technique is to create a button, call it btnQuit, with caption Quit and the following event procedure: Private Sub btnQuit_Click(...) Handles btnQuit.Click End End Sub For statements of the form object.Text = setting the expression for setting must be surrounded by quotes. (For instance, lblName. Text = "Name".) For properties where the proper setting is one of the words True or False, these words should not be surrounded by quotation marks. Names of existing event procedures associated with an object are not automatically changed when you rename the object. You must change them yourself. However, the event that triggers the procedure (and all other references to the control) will change automatically. For example, suppose an event procedure is Private Sub btnOne_Click(...) Handles btnOne.Click btnOne.Text = "Press Me" End Sub and, in the Form Designer, you change the name of btnOne to btnTwo. Then, when you return to the Code window the procedure will be Private Sub btnOne_Click(...) Handles btnTwo.Click btnTwo.Text = "Press Me" End Sub [Page 67]Code windows have many features of word processors. For instance, the operations cut, copy, paste, undo, and redo can be carried out with the sixth through tenth icons from the Toolbar. These operations, and several others, also can be initiated from the Edit menu. The code editor can detect certain types of errors. For instance, if you type txtFirst.Text = hello and then move away from the line, the automatic syntax checker will underline the word "hello" with a blue squiggle to indicate that something is wrong. When the mouse cursor is hovered over the offending wording, the editor will display a message explaining what is wrong. If you run the program without correcting the error, the dialog box in Figure 3.16 will appear. Figure 3.16. Error dialog box. When you double-click on a control in the Form Designer, the header for the most used event procedure is placed in the Code window. The event that appears most frequently in this book is the Click event for button controls. Font properties, such as the name, style, and size, are usually specified at design time. The setting of the properties can be displayed in code with statements such as 1stBox.Items.Add(txtBox.Font.Name) 1stBox.Items.Add(txtBox.Font.Bold) 1stBox.Items.Add(txtBox.Font.Size) However, a font's name, style, and size properties cannot be altered in code with statements of the form txtBox.Font.Name = "Courier New" txtBox.Font.Bold = True txtBox.Font.Size = 16 When you make changes to a program, asterisks appear as superscripts on the page tabs labeled "frmName.vb [design]" and "frmName.vb." The asterisks disappear when the program is saved or run. Beginning with the next section, each example contains a program. These programs are on the companion website for this book. See the discussion on page xv for details. The process of opening a program stored on a disk is referred to as loading the program. You might want to prepare for the next section by loading the program 3-3-1 from the subfolder Ch03 of the Programs folder. [Page 68]Note: After you load the program with the Open Project command from the File menu, you should see the form designer for the program. If not, double-click on the file in the Solution Explorer with extension "vb", that is, frmArithmetic.vb. If the form designer is still not visible, click on the View Designer icon at the top of the Solution Explorer window. Practice Problem 3.2 1. | What event procedure is displayed when you double-click on each of the following controls in the Form Designer? text box button label list box | 2. | Give a statement that will prevent the user from typing into txtBox. | Exercises 3.2 In Exercises 1 through 6, describe the contents of the text box after the button is clicked. 1. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtBox.Text = "Hello" End Sub
| 2. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtBox.ForeColor = Color.Red txtBox.Text = "Hello" End Sub
| 3. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtBox.BackColor = Color.Orange txtBox.Text = "Hello" End Sub
| 4. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtBox.Text = "Goodbye" txtBox.Text = "Hello" End Sub
| 5. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtBox.Text = "Hello" txtBox.Visible = False End Sub
| 6. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtBox.BackColor = Color.Yellow txtBox.Text = "Hello" End Sub | [Page 69]In Exercises 7 through 10, assume that the three objects on the form were created in the order txtFirst, txtSecond, and lblOne. Determine the output displayed in lblOne when the program is run and the Tab key is pressed. Note: Initially, txtFirst has the focus. 7. | Private Sub txtFirst_Leave(...) Handles txtFirst.Leave lblOne.ForeColor = Color.Green lblOne.Text = "Hello" End Sub
| 8. | Private Sub txtFirst_Leave(...) Handles txtFirst.Leave lblOne.BackColor = Color.White lblOne.Text = "Hello" End Sub
| 9. | Private Sub txtSecond_Enter(...) Handles txtSecond.Enter lblOne.BackColor = Color.Gold lblOne.Text = "Hello" End Sub
| 10. | Private Sub txtSecond_Enter(...) Handles txtSecond.Enter lblOne.Visible = False lblOne.Text = "Hello" End Sub
| In Exercises 11 through 16, determine the errors. 11. | Private Sub btnOutput_Click(...) Handles btnOutput.Click Form1.Text = "Hello" End Sub
| 12. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtBox.Text = Hello End Sub
| 13. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtFirst.ForeColor = Red End Sub
| 14. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtBox = "Hello" End Sub
| 15. | Private Sub btnOutput_Click(...) Handles btnOutput.Click txtBox.Font.Size = 20 End Sub
| 16. | Private Sub btnOutput_Click(...) Handles btn1.Click, btn2.Click Me.Color = Color.Yellow End Sub
| [Page 70]In Exercises 17 through 28, write a line (or lines) of code to carry out the task. 17. | Display "E.T. phone home." in lblTwo. | 18. | Display "Play it, Sam." in lblTwo. | 19. | Display "The stuff that dreams are made of." in red letters in txtBox. | 20. | Display "Life is like a box of chocolates." in txtBox with blue letters on a gold background. | 21. | Disable txtBox. | 22. | Change the words in the form's title bar to "Hello World." | 23. | Make lblTwo disappear. | 24. | Change the color of the letters in lblName to red. | 25. | Enable the disabled button btnOutcome. | 26. | Give the focus to btnCompute. | 27. | Change the background color of the form to White. | 28. | Give the focus to txtBoxTwo. | 29. | Describe the Enter event in your own words. | 30. | Describe the Leave event in your own words. | 31. | The label control has an event called DoubleClick that responds to a double-clicking of the left mouse button. Write a simple program to test this event. Determine whether you can trigger the DoubleClick event without also triggering the Click event. | 32. | Write a simple program to demonstrate that a button's Click event is triggered when you press the Enter key while the button has the focus. | In Exercises 33 through 38, the interface and initial properties are specified. Write the program to carry out the stated task. 33. | When one of the three buttons is pressed, the words on the button are displayed in the text box with the stated alignment. Note: Rely on IntelliSense to provide you with the proper settings for the TextAlign property. Object | Property | Setting |
---|
frmAlign | Text | Text Alignment | txtBox | ReadOnly | True | btnLeft | Text | Left Justify | btnCenter | Text | Center | btnRight | Text | Right Justify |
| | [Page 71] | 34. | When one of the buttons is pressed, the face changes to a smiling face (Wingdings character "J") or a frowning face (Wingdings character "L"). Object | Property | Setting |
---|
frmFace | Text | Face | lblFace | Font Name | Wingdings | | Font Size | 24 | | Text | K | btnSmile | Text | Smile | btnFrown | Text | Frown |
| 35. | Pressing the buttons alters the background and foreground colors in the text box. Object | Property | Setting |
---|
frmColors | Text | Colorful Text | lblBack | Text | Background | btnRed | Text | Red | btnBlue | Text | Blue | txtBox | Text | Beautiful Day | | TextAlign | Center | lblFore | Text | Foreground | btnWhite | Text | White | btnYellow | Text | Yellow |
| 36. | When one of the three text boxes receives the focus, its text becomes red. When it loses the focus, the text returns to black. The buttons set the alignment in the text boxes to Left or Right. Note: Rely on IntelliSense to provide you with the proper settings for the TextAlign property. Object | Property | Setting |
---|
frm123 | Text | One, Two, Three | txtOne | Text | One | txtTwo | Text | Two | txtThree | Text | Three | btnLeft | Text | Left | btnRight | Text | Right |
| | [Page 72] | 37. | When the user moves the focus to one of the three small text boxes at the bottom of the form, an appropriate saying is displayed in the large text box. Use the sayings "I like life, it's something to do."; "The future isn't what it used to be."; and "Tell the truth and run." Object | Property | Setting |
---|
frmQuote | Text | Sayings | txtQuote | ReadOnly | True | txtLife | Text | Life | txtFuture | Text | Future | txtTruth | Text | Truth |
| 38. | The user can disable or enable the text box by clicking on the appropriate button. After the user clicks the Enable button, the text box should receive the focus. Object | Property | Setting |
---|
frmTextBox | Text | Text Box | txtBox | | | btnDisable | Text | Disable Text Box | btnEnable | Text | Enable Text Box |
| In Exercises 39 through 44, write a program with a Windows-style interface to carry out the task. 39. | The form contains four square buttons arranged in a rectangular array. Each button has the caption "Push Me." When the user clicks on a button, the button disappears and the other three become or remain visible. | 40. | A form contains two text boxes and one large label between them with no preset caption. When the first text box receives the focus, the label reads "Enter your full name." When the second text box receives the focus, the label reads "Enter your phone number, including area code." | 41. | Use the same form and properties as in Exercise 34, with the captions for the buttons replaced with Vanish and Reappear. Clicking a button should produce the stated result. | 42. | Simulate a traffic light with three small square text boxes placed vertically on a form. Initially, the bottom text box is solid green and the other text boxes are dark gray. When the Tab key is pressed, the middle text box turns yellow and the bottom text box turns dark gray. The next time Tab is pressed, the top text box turns red and the middle text box turns dark gray. Subsequent pressing of the Tab key cycles through the three colors. Hint: First, place the bottom text box on the form, then the middle text box, and finally the top text box. | | [Page 73] | 43. | The form contains a single read-only text box and two buttons. When the user clicks on one of the buttons, the sentence "You just clicked on a button." is displayed in the text box. The program should consist of a single event procedure. | 44. | The form contains two text boxes into which the user types information. When the user clicks on one of the text boxes, it becomes blank and its contents are displayed in the other text box. Note: A text box can be cleared with the statement txtBox.Clear() or the statement txtBox.Text = "". | Solutions to Practice Problem 3.2 1. | TextChanged Click Click SelectedIndexChanged | 2. | Three possibilities are txtBox.Enabled = False txtBox.ReadOnly = True txtBox.Visible = False | |