Computer Science 110 NAME: _________________________ NOTES: module 9 Introducing Visual Basic Events When a Visual Basic program runs, it opens to the user interface. Normally, nothing happens until the user performs an action such as clicking a button on the interface. In the previous module, you learned how to place objects such as buttons on a form and how to set the properties for these objects. As you also learned, these are the objects that appear on the user interface. In Visual Basic, an action such as clicking a button is called an event. Objects cannot respond to events like button clicks unless code is written to tell Visual Basic how to respond when the event occurs. Remember, the three steps to creating a Visual Basic program are: 1. Create the interface—create, position and size the objects, including the form object. 2. Set the properties—set the desired properties for the objects that were created in step 1. 3. Write the code to make the program run. We have already practiced steps 1 and 2. In this module, we will look at step 3—writing some simple code to make our objects respond to some events. Triggering an Event An event is something that happens in the Visual Basic environment. It can be triggered by: A user, when an object is clicked Another program sending a message Something, such as a timer, going off within the program itself Start Visual Basic and create the form as shown: Now, run your program and click the Click here! command button. Nothing happens! There is no response from the program when we click the Click here! button because we have not yet written the code that will determine what happens when the command button is clicked by the user. In other words, we have not told the program what to do when the Click here! event is triggered. Now, go back to your form and double click the Click here! command button. This will open the Code window as shown below. The list box at the top, on the left, shows the name of the currently selected event. (Remember, Click here! is the caption you assigned to the Command1 object.) The list box on the right contains all the events that can be triggered for the selected object, the Click here! button. Click the drop-down arrow to display the list of events, as shown. The Code window displays a default event for the current object, as shown. The default event is the Click ( ) event. In this case, the default click event that is shown is the event that we want. The click event will be triggered when the user clicks the Click here! command button object. The Click here! event code will be written in what is known as a subroutine. The subroutine statements are enclosed between the keywords Private Sub and End Sub. The name of this subroutine is Command1_Click(). Whatever source code you place inside this subroutine will be the instructions that Visual Basic will execute, or run, whenever the Click here! button is clicked. In the next lessons, we will learn how to write the source code that will make up the subroutine statements for some simple Visual Basic events. An Introduction to Writing Event Procedures In Visual Basic, most events are associated with objects. The event that occurs when you click a command button is different from the event that occurs when you click on a Picture object, even though both "events" are triggered by a mouse click. Each of these two events would be specified as follows: Command1_Click Picture1_Click It is the event statements that are written for each click event that determine what the action will be. These statements are written in a block of code called an event procedure. The structure and syntax of an event procedure is shown on the image of the computer screen to the right: An Introduction to Writing Event Procedures Code consists of statements that carry out tasks. In this introductory module on writing code for events, we will limit our code writing to statements that will change the properties of objects while a program is running. To change the properties of an object, we use the structure and syntax shown on the computer screen. Here are three examples of code statements: txtMessage.FontSize = 12 This statement sets the size of the characters in the text box called Message to 12. txtMessage.FontBold = True This statement converts the characters in the text box called Message to bold. Note: For VB2010, the code is: TextBox1.Font = New Font("Microsoft Sans Serif", 12, FontStyle.Bold) To remove Bold, the code is: TextBox1.Font = New Font("Microsoft Sans Serif", 12, FontStyle.Regular) txtMessage.Text = "" This statement clears the contents of the text box called Message. Practicing With Event Procedures In this lesson, we will go through the creation of three event procedures in a step-by-step fashion. We will create the following event procedures: Text1_LostFocus Text1_GotFocus Command1_Click 1. Open Visual Basic and create the interface shown to the right. It will have a form that has one text box and one command button. 2. Set the Text property for Text1 as blank. 3. Change the Caption property for Command1 to Bold. The interface will now appear as shown. 4. Double-click the text box. A window called the Code window will open, as shown. 5. The Object box shows Text1, the current object selected on the Form window. The Procedure box shows Change. Click the down-arrow for the Procedure box. The drop-down menu shows a list of all possible event procedures associated with text boxes. 6. Scroll down the list of event procedures and select LostFocus. The lines of code shown below will appear in the Code window. After your lines of code appear in the Code window: 7. The cursor should be blinking on the blank line. Press the spacebar four (4) times to establish good style. Type the line: Text1.FontSize = 12 8. We have now created an event procedure that is activated whenever the text box loses the focus. The completed event procedure is shown below. 9. Now we will create an event procedure for the text box. Click the Procedure box drop-down arrow and select the GotFocus event from the list. The Code window will now appear, as shown. 10. Establish good style by pressing the space bar four times to indent, then type: Text1.FontSize = 9 Text1.FontBold = False The results are shown below, on the right. 11. Finally, we will create an event procedure for the command button. Click the drop-down arrow for the Object box. The drop-down list contains a list of the objects on Form1, including an object called General. (We will look at this General object in another lesson.) Click on Command1 to select it. 12. Command1 is now displayed in the Object box. The event procedure called Click is now displayed in the Procedure box on the right, as shown. Once the event procedure called Click is displayed in the Procedure box, you should: 13. Press the space bar four times to indent for good style. Type the code for the event procedure as follows: Text1.FontBold = True The event procedure will appear as shown. 14. Run the program by clicking Run→Start or by pressing F5. 15. Click inside the text box and type Cool! Press the Tab key. The contents of the text box will be enlarged, as shown. When the Tab key was pressed, the text box lost the focus. This means that the event, LostFocus, happened to Text1. In programming terms, we say that the event procedure Text1_LostFocus was called and the code inside the procedure was executed. Once the contents of the text box are enlarged, as was shown on the previous screen: 16. Click the Command button labelled Bold. This calls the event procedure Command1_Click. When the code executes, the text in the text box will be changed to boldface type, as shown. 17. Click on the text box to move the cursor to the text box. This changes the focus back to the text box by calling the event procedure Text1_GotFocus. This procedure restores the text to its original size, as shown. 18. Repeat steps 15 to 17 as many times as you want until you are clear as to what has happened, then stop the program by clicking Run→End. 19. Save your project in your Practice folder as MyEventProcedures. Note: You will need to use this project again in the next lesson. A Better Ending! Up until now, we have ended our programs by clicking Run→End on the Menu bar. A better technique for ending Visual Basic programs is to create a command button that will end the program. We will create such a button and its event procedure in this lesson using the following steps: 1. Start Visual Basic and open your MyEventProcedure project. (Created in the previous lesson and saved in your My Documents/Practice folder.) 2. Add a second command button to the interface, as shown. 3. Double-click the Quit button to open the Code window and set the event procedure as follows: Sub Command2_Click () End End Sub 4. Run the program. Type something into the text box and then click the Bold button. Now click the Quit button to end the program. 5. Resave your project. An Application Walk-through In this lesson, we will go through the creation of a new project from beginning to end. As we move through the steps of the activity we will: Add objects to a form. Set properties for the objects. Resize and move an object. Save the project. Run the application. Change the properties of the form object and other objects on the form. Write event procedures. Print the project. Use the assignment operator to change property values. Remove the project from the IDE. Create an executable file. A long time ago, a very simple application was created as an example of a program in the C language. This program was named My First C Program. All this program did was print the phrase, "Hello, world!" to the screen. Since then, the Hello, World! application has become a sort of ritual introduction to new programming languages. In this next activity, we will create our own version of Hello, World! with Visual Basic. Hello World! Example Here is the Hello, World! application, Visual Basic style! 1. Start Visual Basic. 2. Create a new project. 3. Every Visual Basic application has at least one form. Set the following properties for your form: Property Value Name frmHelloWorld Caption Greetings 4. Objects can be added to the form at design time. Design time refers to the time during which the application interface is being created. Add a label object and a command button to your form, as shown. 5. Set the label properties as follows: Property Value Name lblHelloWorld Caption Hello, world! Font Arial, bold, 14 Alignment Left justify 6. Set the command button properties as follows: Property Value Name cmdDone Caption Done 7. Resize the label object so that the phrase Hello, World! appears on one line, as shown. 8. Save your HelloWorld project in your Practice folder. Click File->Save Project As. When a project is first saved, both the form and the project must be given descriptive names. Good programming style is to save the form using the same name as its Name property (frmHelloWorld) and then save the project with a name descriptive of the application. For example, the HelloWorld application should be saved as HelloWorld. 9. Open your HelloWorld project. Run the HelloWorld application by selecting Run->Start or by clicking the Start button on the toolbar. A Visual Basic application can be run at any time during its development. This allows testing of the application as you write it. To stop the application, click Run->End or click the End button on the toolbar. 10. An application will contain program code that tells the computer how to perform a specific task. Each line of code is called a statement. Programs can contain many, many lines of code. Double-click the Command1 button (with the caption Done) to open the Code window. The Code window displays the cmdDone Click( ) event procedure, as shown. 11. We will write code that uses one of Visual Basic's built-in functions, the Unload function. We will write an Unload statement that will remove the form from memory and end the application. The Unload statement requires a form name. The event procedure is shown as: 12. Private Sub cmdDone_Click() End Sub cmdDone is the object name. _Click() is the selected event name. Private indicates that the procedure cannot be accessed outside of the form. Sub declares the procedure. End Sub is required to end the Sub statement. Between these statements is where you will write the body of the procedure. The body will contain the code that tells the application how to respond to the button click event procedure. 13. Position the cursor between the Private Sub and End Sub lines. Press the spacebar four times to follow proper style convention. Type the line of code as shown: Unload frmHelloWorld Unload is a built-in Visual Basic function. frmHelloWorld is the name of the form that will be unloaded when the Done button is clicked. 14. When complete, the code for the event procedure should be as shown: 15. Run the application again. Click the Done button. Clicking the Done button triggers the event procedure. The code tells Visual Basic to unload the HelloWorld form. 16. Print the interface and application code by selecting File->Print on the Menu bar. A dialogue box will open, as shown. 17. The Print What options in the dialogue box are used to print either the form, the code or the form as text. Selecting OK prints the options you have selected. Select Form Image and Code, then click OK. 18. Once you have finished working with a project, it should be saved and closed. Close your project by selecting File->Remove Project from the File menu. The project will be removed from the Visual Basic IDE. 19. In many applications that you develop, it will be necessary to change the value of an object's property at run time. Add two command buttons to your HelloWorld application. Set the properties for each button as follows: Table 1: Command1 Property Value Name cmdFrench Caption French Table 2: Command2 Property Value Name cmdSpanish Caption Spanish 20. The HelloWorld form should now look like the following: 21. Now we will add the code that will translate the phrase Hello, World! into French when the French button is clicked. Double-click the French button. Using proper indenting style, add the following code statement to the Private Sub cmdFrench_Click ( ) event procedure: lblHelloWorld.Caption = "Bonjour, monde!" 22. Double-click the Spanish command button to open the Code window. Using proper indenting style, add the following code statement to the Private Sub cmdSpanish_Click ( ) event procedure: lblHelloWorld.Caption = "Hola, mundo!" 23. Click File->Save Project on the Menu bar. The Code window should now look as shown: 24. Next, we will comment our code. Place your cursor at the end of the code statement in the cmdFrench_Click() subroutine and add the following comment to the end of the statement: 'translates greeting into French Place your cursor at the end of the code statement in the cmdSpanish_Click() subroutine and add the following comment to the end of the statement: 'translates greeting into Spanish 25. Resave the project by clicking File->Save Project on the Menu bar. Close the Code window. 26. Run your application. Click the French button and the Spanish button. 27. An application that includes graphics is more interesting to interact with. Click here to download the image to your My Documents\My Pictures folder. You will use this image in the next part of this exercise. 28. Add an image object to your HelloWorld application. 29. From the Properties window, double-click the Picture property. In the values column, click on the ellipsis, navigate to your My Documents\My Pictures folder, where you downloaded the image in the previous step. Select the image called globe. 30. Set the properties for the image object as shown: Property Value Name imgGlobe Picture globe (from your My Documents\My Pictures folder) Stretch True Visible True 31. Arrange your interface so that it is similar to: 32. Resave your project by clicking File->Save Project. 33. Visual Basic includes a compiler that translates the program code into a separate executable file. An executable file can be run independently of Visual Basic on any computer that uses Windows 95 or higher. On the Menu bar, select File->Make HelloWorld.exe. The Make Project dialogue box will be displayed. 1. In the Save in box, navigate to your My Documents folder. 2. In the File name box, type HelloWorld, if it is not already displayed. 3. Click OK. Visual Basic will create the executable HelloWorld application called HelloWorld. 34. Exit Visual Basic by clicking File->Exit. 35. The HelloWorld executable file may be run from Windows just like any other application. From the desktop, navigate to your My Documents folder and double click the HelloWorld file to launch the application. Errors and the Visual Basic Development Environment Visual Basic uses an interpreter that automatically reads each line of program code as it is entered. If a statement has an error, Visual Basic highlights it immediately so that it can be corrected. Visual Basic can detect certain types of errors. Let's look at the following line as an example: Text1.FontSize = 12 If you had forgotten to type the number 12 in the line of code before pressing the Enter key, Visual Basic would tell you something was missing by displaying the message shown in the image on the right. Notice that the line of code in which the error occurs is displayed in red.
© Copyright 2024