Hour 20
Programming with Visual Basic 2019

Unlike with many other programming languages, much of the work of a Visual Basic programmer doesn’t lie in code but in the design of the application’s visual elements, such as the controls that the programmer places on forms at design time. These controls allow interaction both to and from the user. The code that the programmer places behind the controls handles the events as well as data calculations and manipulations that produce the information required by the program.

This lesson is intended to introduce you to Visual Basic and Microsoft’s Visual Studio environment. As in other lessons in this section, you will only be getting a taste of the language, but if you like it, you can dive deeper into Visual Basic with a tutorial book such as Sams Teach Yourself Visual Basic 2015 in 24 Hours, from Sams Publishing.

The highlights of this hour include the following:

Image How to set control property values

Image How to embed code within a Visual Basic application

Image How to place and size controls so they look correct on the form

Image What kind of code appears in a Visual Basic application

Reviewing the Visual Basic Screen

Unlike most other programming languages, Visual Basic is and always has been a Windows programming language. When you learn to write programs with Visual Basic, you learn not only the language but also its environment. Visual Basic is part of Microsoft’s Visual Studio, a shared integrated development environment (IDE) where you can develop in Visual C++, Visual C#, Java, JavaScript, Python, and F#. The advantage to a shared IDE like this is that once you learn the ins and outs of using the editor and tools of one programming language, you’ve got a head start on your next language. Before you can do anything in Visual Basic, you must understand the Visual Basic screen.

Note

This hour assumes that you’ve installed the Visual Studio environment and focuses on using Visual Basic 2019. If you need help installing Visual Studio, you can find many online resources to help.

Figure 20.1 shows the Create a New Project screen with Visual Basic Windows options selected. This screen offers a rich variety of options, and across the top of the window, you can filter by language (Visual Basic in the sample screen), Platform (Windows in this example, but you can also choose Android, Azure, iOS, Linux, MacOS, tvOS, or Xbox), and Project Type (All Project Types in this case). In addition, there are more template choices, depending on the languages and the submenu (for example, Windows, Web, Office). You can always select Empty Project and build your offering from scratch, but a template gets things started for you. Much of what you do with Visual Basic is Windows based, so Blank App (Universal Windows) is a common starting point.

images

FIGURE 20.1
When you start a new Visual Basic project, you have a rich variety of options.

A Windows application is often composed of several files, including the following:

Image Form files: This type of file contains a form and its description, controls, and related event procedure code.

Image Code modules: These modules hold general-purpose code.

Image Other files: Other files contain elements needed by the application.

The Project window keeps track of all items within an application.

The term project is used to describe a collection of all files that compose a single Windows application. (The Project window is often called the Project Explorer window because of its tree-structured nature that mimics the Windows Explorer program.) The Form Layout window lets you determine, by dragging with your mouse, the location of the current form on the user’s screen when the user runs the program.

Caution

Depending on the version of Visual Studio you have, you may see slightly different screens from the ones presented here. Figure 20.1 shows the project options in Visual Studio 2019 Professional. Other versions of Visual Studio have fewer options to select. Don’t worry, though. Windows Form Application, covered in this hour, is a universal option in all Visual Studio installations.

The latest versions of Visual Basic include tools that go far beyond those available in most other languages. However, creating a Visual Basic application from scratch involves little more than these steps:

  1. Design the application by stating its goals and detailing its requirements.

  2. Place graphics controls on the application’s Form window. (This is the output definition design stage.) As you place the controls, you’ll assign many of the initial properties to the controls.

  3. Add event procedures that handle control events.

  4. Add any other code needed to tie the controls together and process data as required by the application.

  5. Test and distribute the application to users.

As you’ll see in the next section, Visual Basic can greatly help reduce the time it takes to complete steps 2 through 4.

Creating a Simple Application from Scratch

With just a single lesson on Visual Basic, you might as well take the plunge into the creation of a program from scratch. However, if you don’t have access to a Visual Basic programming environment, reading through this section still has some value. You can follow along to get an idea of what Visual Basic requires when you create applications.

This first application you’ll create in this lesson displays a picture and a command button. The program will change the picture when you click the command button. Follow these steps to create this simple application:

  1. After starting Visual Studio, select Create a New Project to display the New Project list (refer to Figure 20.1).

  2. Type Windows Form in the search bar and highlight Visual Basic as the language and Windows as the platform. Make sure Windows Form App is highlighted and click the Next button.

  3. Enter TYBeginProgVB as the project name—or feel free to name it something more clever. You can also change its location from the current default if you wish.

  4. Click Create. Visual Basic adds a single form (currently named Form1) for you to start building your project.

    Note

    The small white squares that appear on the right side, bottom, and bottom-right corner of the form are sizing handles that you can use to change the width or length of your form. Notice that the Properties window in the bottom right displays properties of the form.

  5. Drag the form’s lower-right sizing handle down and to the right. As you drag the form, notice the changing width and height measurements at the right of the toolbar. Size the form so that it measures about 740×520 pixels. If you want to be exact in the size of the form and you are finding that stretching the form with the sizing handles is too difficult, click the plus sign next to the Size information in the Properties window. Two lines, Width and Height, appear. You can then type the specific data you want, and the window instantly resizes to the size you specified. Figure 20.2 shows the screen.

    images

    FIGURE 20.2
    When you resize the form window, you are resizing your application’s program window.

    Note

    The size of the window is measured in pixels, a refreshing change from early Visual Basic versions that used twips. Twips were screen units used commonly during programming screen controls. The number of twips was somewhat dependent on hardware, but the general calculation of a twip was approximately 1/1,440 of an inch. That is, there were 1,440 twips to an inch. Switching to pixels made much more sense as pixels are a more universal measurement to computers in general.

  6. To see how to work with the Properties window, assign a better name than Form1 to the form. In the Design section, a property called (Name) (enclosed in parentheses to keep the name at the top of the alphabetical property list) holds the selected form’s name. (In the future, this lesson omits the parentheses from around the Name property.) Scroll up the Properties window, if necessary, until you see the Name value and notice that the Name value is currently assigned Form1.

  7. Click the form’s Name property and type frmMyFirst for the form name.

    Tip

    You change and assign all properties inside the Properties window the same way you just changed the form’s name. Scroll to a property, click the property, and enter (or select for those properties with drop-down list boxes) a new property value. Notice that the name frmMyFirst is more descriptive than Visual Basic’s default form name, Form1. Get in the habit of changing the default object names to make them more representative of what they label. Better naming makes your program easier to maintain.

  8. Change the form’s title bar from its original value to Hat Picture Application by selecting the Text property in the Appearance section and typing Hat Picture Application. The Text property determines what appears in the form’s title bar when the user runs the program. The new name appears in both the Properties window and the form’s title bar and helps describe the picture this application will produce.

  9. Now that the application’s background is complete, you are ready to add the details by putting controls on the form.

Adding the Details

Adding controls to a form typically involves one or more of these steps:

  1. Select the control from the toolbox.

  2. Place the control in its proper location.

  3. Size the control.

  4. Set the control’s properties.

  5. Activate the control with Visual Basic code, if needed.

In the steps that follow, you’ll quickly learn how to place controls on the form you've already created. Generally, you perform these steps in one of two ways:

Image Double-click the control’s icon on the toolbox. Visual Basic places that control in the center of the form. You can then drag the control to its proper location and size the control by dragging its sizing handles in or out.

Image Click the control’s icon on the toolbox and move the resulting crosshairs mouse cursor to the form where the control is to be placed. Click and hold your mouse button where the control is to start. As you drag the mouse, Visual Basic draws the control’s outline on your form. When you’ve drawn the control at its proper location and size, release the mouse button to place the control.

Follow these steps to spruce up the application you began in the previous section:

  1. Double-click the Label control so that Visual Basic places the label in the center of your form. The Label control contains the letter A. (ToolTips pop up to let you know what a toolbox icon is for.) The label is now the selected tool on your Form window editing area, so the sizing handles appear around the label. In addition, the Properties window changes to show the label’s properties, and the toolbar’s location and size coordinate pairs now reflect the label’s measurements. A label displays text on a form. This new label will hold a title banner for your application.

  2. Drag the label up the form until it rests approximately 340 pixels from the left edge of the form window and 20 pixels from the top of the form. Again, you can use the Location values in the Properties window to type in exact values if you don’t want to mess with dragging it around.

  3. In the Properties window, scroll down to the text control and type your title. The default font and size are a little bland, but you can use the font properties to alter its style, size, and any effects, much as you would do in a word processor. If the text for this box has caused the box to lose its centering, feel free to go back and tweak the positioning of the label.

  4. Click the Toolbox button in the upper-left corner to bring back the choices and double-click the toolbox’s Button control to place a button in the center of your form. The icon on each choice in the toolbox should illustrate the purpose of the button. You can also point to any button to see a ToolTip pop up at the mouse pointer that shows the name of the button. Use the other properties to alter the size of the button and the style and size of the font for the button’s text label that you can change from Button1 by typing in the words in the Text Property box.

  5. Locate the toolbox’s PictureBox control. Instead of double-clicking to place the control as you did with the label, click the control’s icon once. Move your mouse to the Form window and draw the Image control, trying to first anchor the image at 260 pixels from the form’s left edge and 210 from the form’s top edge. Size the image at approximately 220 pixels wide and 190 pixels high. Again, you can do this by meticulously dragging the handles so that Visual Basic’s ScreenTips pop up, showing you the coordinates of the image. When the coordinates appear at their proper size, release your mouse button to place the image at that size. Or you can type the information into the Location and Size property boxes. (I find the latter option to be much easier.) Figure 20.3 shows the screen at this point. The PictureBox control displays a graphics image when you run the program.

    images

    FIGURE 20.3
    Your application is taking shape.

    Tip

    The sample application is not exactly centered at this point. You can use some simple math to center align your controls if you wish. Simply divide the size of the form in two. (In this case, the form is 740 pixels, so half would be 370.) Then take the size of your controls, divide them in half, subtract that number from the number you calculated as half the form size, and that should be the first number of the location of your form. It sounds complicated, but when you do it a couple times, it gets easy. So if the label is 300 pixels wide, it should start at 220 pixels in order to be centered.

    Note

    Location pixel coordinates and size pixel coordinates are always specified in pairs. Often, you’ll see such coordinate pairs specified inside parentheses, as in a location value of (250, 280). For the coordinates, such a pair of values would signify that the width is 250 pixels, and the height is 280 pixels.

Now that you’re more familiar with setting property values for controls, even though you may not understand many of the properties yet, you are equipped to set additional properties for the form and controls to finalize the look of the application. After you set appropriate property values, you will add code to connect the controls and make them work together.

Table 20.1 contains a list of properties that you would need to set for the form and the three controls in order to match. Remember that you must select the form or specific control before you can change property values for that form or control. To select the form, click anywhere inside the form or title bar—but not over any of the controls. The Properties window will change to display the form’s properties. Click either the label, command button, or image to select the control, and then you can change one of that control’s properties by clicking the property name and typing the new value.

TABLE 20.1 Property values to set for the application’s form and controls

Control Property Property Value
Form MaximizeBox False (open the drop-down list box to see values)
Label AutoSize False (open the drop-down list box to see values)
Label Name FranPlace
Label Text Welcome to Fran's Place
Label Font Showcard Gothic
Label Font.Bold True
Label Font.Size 11.25
Label Location 220,30
Label Size 250,20
Image Name ProductPicture
Image Location 240,140
Image Size 220,190
Command Button Name FranPic
Command Button Text Pick a Product

Finalizing with Code

You can add Visual Basic programming statements to turn your creation into a working, although simple, application. Visual Basic automatically adds the opening and closing statements needed when you write a subroutine, as you’ll see in the following steps:

  1. Double-click the command button to open the Code window. A set of beginning and ending statements appears for a new procedure related to the command button that looks like this:

    Private Sub FranPic_Click() Handles FranPic.Click
    End Sub

    These lines are two of the three lines needed for code required by the command button. The Code window works like a miniature text editor, in which you can add, delete, and change statements that appear in your program code.

    Note

    All code appears in procedures, and every procedure requires beginning and ending lines of code that define the procedure’s start and stop locations. Visual Basic automatically adds the first and final lines of many procedures.

  2. Press the spacebar three times and type the following line between the two lines that Visual Basic provided for you (specifying your own directory path as it will probably not match the one below):

    ProductPicture.Image = Image.FromFile("C:DocumentsTY Begin 24product1.jpg")

    As soon as you type Image.FromFile, Visual Basic offers pop-up help with the statement’s format. Some Visual Basic statements, especially those with parentheses, such as the ones you see in this statement, require that you type one or more values. Visual Basic pops up the format of these required values so you know how many to enter. You’ll learn more about why these values are required if you decide to pursue the language in more depth. Visual Basic is a large language, and this help comes in handy.

  3. Run the program and click the command button. A picture appears, as shown in Figure 20.4. You have successfully completed your first Visual Basic application. You’ve created an application that displays a picture when you click the command button. The application contains code, and its controls all have property values that you’ve set.

  4. Click the Close window button to terminate the program. Be sure to save your project before you exit Visual Studio.

images

FIGURE 20.4
Your application produces a graphics image when you click the command button. (Credit: Pavel Losevsky/123RF)

Other Visual Basic Programming Considerations

This hour approaches the Visual Basic language differently from most other languages discussed in these 24 hours. Instead of walking you through specific programming language commands, this hour walks you through the steps required to create a sample application from start to finish. If you look back through this lesson, you’ll notice that very little of the discussion includes actual programming language statements. Visual Basic does a lot just using a visual environment, and adding code sometimes seems like an afterthought.

Even adding menus to the Visual Basic applications that you create from scratch is relatively simple because of a tool called the MenuStrip control (see Figure 20.5). The MenuStrip control lets you build a menu bar and the pull-down options from that menu bar by selecting and specifying options. No code is required as you add the menu options to your application, but after you use the MenuStrip control to add the options, you have to specify event code procedures for the menu options. When the user selects a menu option, a Click event for that menu option occurs, and each event procedure that you write tells Visual Basic how to respond to that event.

images

FIGURE 20.5
Use the MenuStrip control in the toolbox to add menu options to your Visual Basic application.

Understanding Procedures

Consider the following event procedure for the File, Exit menu option:

Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs)
    Handles ExitToolStripMenuItem.Click
         ' Terminates The Program
          End
    End Sub

By studying this simple procedure, you can learn quite a bit about all event procedures. The Private keyword indicates that the procedure is local to the current form and cannot be called by other form modules. Therefore, if several forms exist in the current Windows application, selecting File, Exit from this form will execute this specific event procedure and not one outside the scope of this form. The opposite of Private is Public, and public procedures are available to any code in the entire application. Such public procedures are known as global procedures because any procedure in the application can call them.

The keyword Sub or Function always follows the Private (or Public) keyword and indicates the type of the procedure. A subroutine is a procedure that always performs work and then returns control to whatever code was executing before the event took place. A function is a procedure that always performs its job when the event takes place and then returns a value to another place in the program that might need that value.

The name of the event procedure specifies exactly which control and event this procedure responds to. The body of the procedure may consist of several lines, but this one happens to include only two lines: a remark and the End statement, which stops the running program. Every procedure ends with an End Sub or End Function statement. The parentheses that follow the procedure name indicate that the code begins a new procedure; sometimes, when one procedure must pass data values to another, you list one or more values separated by commas inside the parentheses. Even if you don’t pass data, you must type the parentheses after every procedure declaration.

Understanding the Language Behind Visual Basic

The language behind Visual Basic has significant differences from the Python you’ve learned to this point, but the concepts are similar: You just need to understand the tweaks you must make to the syntax of loops, conditional expressions, and assignments. Visual Basic also includes several statements that are unique to the Windows environment.

One of the ways that Visual Basic is unique, however, is in its distribution of procedures across different areas of an application. You now know that several small event procedures reside in a form’s Code window to handle any events that occur on that form. Other forms can exist as well, and code appears in them to handle events that occur there. In addition, other files might be part of a complex application. A code module is a file, separate from any form and the form’s associated code, that holds code that you might use in more than one application. Suppose that you write a procedure that prints your company logo at the top of a page. Such a logo would appear before any report that you produce, before any accounting statement, and before anything you print. You could use this procedure in many different applications.

Instead of typing the procedure in every application that needs it, you can put the code in a general-purpose code module that you then can copy into a new code module for all applications that need to produce the logo. You can, from anywhere else in the application, call a Public general procedure with a Call statement such as this:

Call logoPrint   ' Detour to the procedure

When the Call statement finishes, execution returns to the statement that follows Call.

Your Next Step

This hour offers only a walkthrough of the steps that you take to create a Visual Basic application, and it provides some insight into the nature of Visual Basic programming. Although Visual Basic is probably the easiest programming tool available for creating Windows applications, Visual Basic is vast compared to simpler languages such as JavaScript. Therefore, an hour’s lesson could not hope to cover more than what is included here. Nevertheless, you now have a firm grasp of what it takes to write Windows applications in Visual Basic.

Tip

If you want more in-depth Visual Basic programming coverage, pick up a copy of Sams Teach Yourself Visual Basic 2015 in 24 Hours, from Sams Publishing, which explores Visual Basic programming and takes a beginning Visual Basic programmer to advanced levels in 24 lessons.

Summary

Visual Basic is more than a language; it is part of a complete Microsoft programming environment called Visual Studio. Other languages are available for Visual Studio, such as Visual C#. Visual Basic was the first language to use the Visual Studio environment. When you create a Visual Basic application, you first create the visual elements of the program by placing the controls from the Toolbox window onto the form. As you place the controls, you set the properties and then write event procedure code to activate the controls when certain events take place.

The next hour describes another language within Visual Studio, C#, as well as Microsoft’s overall .NET strategy.

Q&A

Q. Could I allow users to pick an image instead of displaying a specific image when they click a button?

A. Absolutely. With Visual Basic you can use most controls you see in Windows-based programs, so you can trigger a dialog box that lets users browse their hard drive and select an image of their choice instead of using a predetermined file.

Q. Do all Visual Basic applications contain code in addition to event procedures?

A. Some Visual Basic applications contain code that forms event procedures only, but most other Visual Basic applications contain other kinds of code. Most applications have more than events going on. Data must be processed, calculations must be performed, reports must be printed, and files must be read and written. The code behind these specific tasks often appears in a code module separate from the form module.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. How much code do you have to write to add Internet access to a Visual Basic application?

2. What toolbox control would you use to add menus to a form?

3. Why is it a good practice to change the names of controls from their default names that Visual Basic assigns?

4. What happens when you double-click a toolbox control?

5. What tool do you use to create menus for Visual Basic applications?

6. How does Visual Basic determine which control properties appear in the Properties window?

7. Name one advantage to running a Visual Basic application inside Visual Basic’s environment as opposed to running a compiled application from Windows.

8. Which runs faster: a Visual Basic application running inside Visual Basic’s environment or a compiled Visual Basic application running outside Visual Basic’s environment?

9. What information can you gather from the following Visual Basic procedure’s declaration line?

Private Sub scrMeter_Change()

10. True or false: All Visual Basic procedures reside in the application’s form module.

Answers

1. You don’t have to write any extra code to add Internet access to a Visual Basic application.

2. You use the MenuStrip control.

3. The default names are not meaningful, and when your application uses several controls, you should name those controls with names that you will recognize when maintaining the program so you modify the correct controls when needed.

4. The toolbox control appears in the center of your Form window.

5. The Menu Editor helps you build and test menus.

6. The control you place on a form determines which properties appear in the Properties window.

7. You can debug the application inside the Visual Basic environment.

8. A compiled Visual Basic application is faster than an application run inside the Visual Basic environment.

9. The procedure is private, which means only the enclosing program can access the procedure, the procedure is a subroutine so it does not return any values, and no arguments are passed to the procedure.

10. False. Some procedure code can appear in code modules.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.143.31