Introduction to Windows Forms Applications: Using Visual Basic 2005 Express Edition

Lou Tylee

KIDware

February 2007

Overview

So you’ve installed Visual Basic Express Edition on your computer and now you want to know what to do with it. Visual Basic is one of the easiest programming languages to learn. Yet, even though it is easy to learn and to use, Visual Basic can also be used to develop very powerful computer programs. The Visual Basic Express Edition provides a sophisticated environment for building and testing Windows-based applications. This lesson will introduce you to the idea of Windows Forms applications using Visual Basic Express Edition.

You’ve used Windows Forms applications before. Microsoft’s programs like Word, Excel, PowerPoint, Internet Explorer and the windows that appear within these applications (to open and save files, to print files) are all Windows Forms applications. These applications may not be written in Visual Basic, but they do demonstrate the functionality you can put in your Visual Basic Express applications. You can do just about anything using the Visual Basic programming language – you can write computer games, manage enterprise systems and databases, develop web applications, and build Windows Forms applications to help with tasks in your everyday home and work life.

You will learn about Windows Forms applications by opening and running a sample project in the Visual Basic Express development environment. The sample project is called Hidden Note. It is a simple note editor that allows you to write and save text files in an encrypted fashion. These files can only be read when opened in the Hidden Note program, not by someone browsing through your file folders. So, before starting, you need to make sure you have this example project on your computer. To do this, please make sure you have downloaded the accompanying source code project files from the Beginner Developer Learning Center website and saved them in a folder on your computer.

Now, let’s get started. Follow these steps to get Visual Basic Express running on your computer:

  • Click on the Start button on the Windows task bar.

  • Select All Programs, then Microsoft Visual Basic 2005 Express Edition

(Some of the headings given here may differ slightly on your computer, but you should have no trouble finding the correct ones.) The Visual Basic Express program should start. Several windows will appear on the screen, with the layout depending on settings within your product.

Opening the Sample Visual Basic Express Project

What we want to do right now is open a project. Windows applications written using Visual Basic Express are referred to as solutions. A solution is made up of one or more projects. Projects include all the information we need for our computer program. Most times, the words project, solution, program and application are used synonymously.

We will open the sample project using the Visual Basic Express development environment main menu. Follow these steps:

  • Select File from the main menu, then click Open Project. An Open Project window will appear:

Bb297400.caec5179-ff0a-44ab-a641-eaebab80b454(en-US,VS.80).png

  • Go to the Hidden Note folder containing the sample project.

In this project folder, among other things is a Visual Studio Solution file named Hidden Note.sln and a Visual Basic Express Project file named Hidden Note.vbproj. Open the Hidden Note solution file (as shown in the example Open Project window). Since there is only one project in this solution, you could also open the project file and get the same results, but it is better to always open the solution file.

Your Visual Basic Express project may look something like this:

Bb297400.3d533df9-5c4e-4a75-b4d3-d582bbd67e37(en-US,VS.80).png

Look for the Solution Explorer window usually placed in the upper right side of the screen. If it is not there, choose View in the menu and select Solution Explorer. This lists the files in our solution. Right-click the file HiddenNote.vb file and choose Open. This is the main Windows Form in the Hidden Note project (we will look at the other Password.vb Windows Form later on).

When the HiddenNote.vb Windows Form is opened, Visual Basic Express is in design view mode. This is the mode used to visually or graphically build Windows Forms applications. As opposed to the code view mode which shows the actual source code text of the application (we’ll cover the code view mode later on). In the Design window (the HiddenNote.vb [Design] tab) will appear a form that looks something like this:

Bb297400.9540bf99-66f3-4a79-be04-52f610f13ed6(en-US,VS.80).png

This is one of two forms used in our project. It is the form where you or a user will write a note to be saved. We’re going to spend a bit of time explaining everything that is displayed here. This will introduce you to some of the vocabulary we use in Visual Basic Express.

As mentioned, we call the displayed project window a Form. You have probably noticed that all Windows applications are built using forms of some type. At the top of the form is the Title Bar. It has an icon (little picture) related to the form (a notepad in this case), a title or description of what the form does (Hidden Note), and three smaller buttons that control form appearance. You may recognize the Minimize, Maximize, and Close buttons that are common on most windows applications, but we won’t worry about these buttons right now.

Bb297400.dcd1cfad-2e4b-40ba-8cc6-5a2a22ef52f4(en-US,VS.80).png

At the top of the form is a toolbar with four buttons with pictures on them. There is a large area under the toolbar where you can enter and edit text (a text box). Below the form are three other items (named tbrNote = ToolStrip control that hosts the buttons at the top of the form, dlgOpen = OpenFileDialog control, and dlgSave = SaveFileDialog control). The toolbar buttons, text area on the form, and the things below the form are called Controls or Objects. Controls provide an interface, or line of communication, between you (or the user of your program) and the computer. You use the controls to tell the computer certain things. The computer then uses what it is told to determine some results and displays those results back to you through controls. By the way, the form itself is a control. If you’ve used any Windows applications, you’ve seen controls before - you probably just didn’t know they were called controls. As examples, check boxes for choices are controls, scroll bars to move through word processor documents are controls, menu items are controls, and the buttons you click on when opening and saving files are controls.

Controls for projects are selected from the toolbox:

Bb297400.e89ca947-8cde-4de4-bec7-744d23c89ea4(en-US,VS.80).png

If the toolbox window is not present on the screen, click View on the main menu, then Toolbox. Controls are grouped into categories according to what they do. To see a list of all the controls, make sure you have the All Windows Forms category group expanded. Scroll down the list to see all the controls. Many of these controls should look familiar to you. They are the same controls used in many Windows applications – such as a Button, a ComboBox, a PictureBox, etc. During design, controls are moved from the toolbox to the form by a simple drag and drop process. If you would like, you can add a new form to the project (from the main menu select Project | Add Windows Form | Click ‘Add’ button) and drag and drop various controls onto this new Form1 to experiment with their functionality.

Every characteristic of a control (including the form itself) is specified by a property. Properties are used to give your project the desired appearance. Example control properties include names, any text on the control, width, height, colors, position on the form, and contents. Initial properties for controls are set using the Properties Window which is usually located on the bottom right:

Bb297400.300a2d71-3616-4917-a537-1d284830f1a3(en-US,VS.80).png

If the properties window is not present on the screen, click View on the main menu, then Properties Window. Click the Properties button (next to the Alphabetic view button) to see the properties. The drop-down box at the top of the window lists all controls on the current form. Under this box are the available properties for the currently selected object (frmNote in this case). Different views of the properties are selected using the toolbar near the top of the window. Two views are available: Alphabetic and Categorized. The properties are listed on the left side. The current value is listed on the right side. Clicking on the current value allows editing. Try changing some of the values for these properties – for example, try changing the BackColor property to a different color, or the Text property to something else.

As we mentioned before, this project will allow you to write and save encrypted messages. To open these messages, a user will have to enter a secret password. Now let’s take a look at the other Windows form in this sample project: Password.vb which is used to accept the password. Go back to the Solution Explorer window. Right-click the file Password.vb and choose Open.

In the Design window (the Password.vb [Design] tab), you will now see this:

Bb297400.bac6472b-76a3-4ccd-9be3-7d3171cecc49(en-US,VS.80).png

Note the different title bar and icon (a padlock). There are also other controls on this form. There is a text area to type the password, a button to click once the password is entered and a check box to allow remembering the password. Go ahead and examine the different properties and values for each of these controls.

I think you get the idea that controls are a very important part of a Windows Form application, and you’re right. They are what allow your application to communicate with users – both to gather user input as well as to display output to users. Now, let’s run this example and get some insight into how this application and its controls works.

Running the Sample Visual Basic Express Project

After opening a Visual Basic Express Windows Form application, you want to start or run the program. This gets the program going and lets the user interact with the controls on the form and have the computer do its assigned tasks. We can run a project by using the toolbar under the Visual Basic Express menu. Look for a button that looks like the Play button on a VCR, CD player, or cassette tape player:

Bb297400.126481c6-99d9-4ba6-b29c-75a5959b3263(en-US,VS.80).png

  • Click this button to run Hidden Note (the project we opened previously).

You can also run a project by: (1) selecting the Debug menu heading, then clicking Start Debugging, or (2) pressing the <F5> function key.

The HiddenNote form will appear and look something like this:

Bb297400.b1220b2b-aeb1-4503-a4f2-e8cf18fe4083(en-US,VS.80).png

Notice the items we saw below the form are not visible, that’s because those controls (tbrNote, dlgOpen, dlgSave) do not provide a graphical user interface and thus do not need to be displayed on the Windows Form. Also, notice in the Visual Basic Express title bar (in the main window) that the word Running appears in parentheses next to the project name:

Bb297400.914a8f5b-e5ce-43c2-986b-d5dbdf8c2d88(en-US,VS.80).png

It is important to always know if you are running or designing a program – this indication in the title bar will tell you.

The project is now running, but what is it doing? Nothing is happening, or is it? At this point, Visual Basic Express is waiting for you, the user, to do something. We can say that your Hidden Note project is waiting for an event to occur. Nothing can happen in a Visual Basic Express Windows Form application until an event occurs. We call Visual Basic an event-driven programming language. So, let’s cause an event.

An event occurs when you do something on the form - click on something with the mouse, type something in places where words can go, or maybe drag an object across the form. Hold your mouse over each of the toolbar buttons. A tooltip should appear telling you the function of each button. When the mouse moves over a button, we cause an event called a MouseOver event (the mouse has moved over the button). Click the button to open a note (the button with the folder). Doing this causes a Click event on the button. The Open File dialog box should appear:

Bb297400.e9987c74-c06a-43a4-b8d2-24b39ad449ed(en-US,VS.80).png

Where did this come from? Remember the items under the HiddenNote form we saw when we displayed the form?

Bb297400.2e9fd6e5-81c8-46b1-afb5-826cb1fcafbb(en-US,VS.80).png

These items are also controls, but controls that appear only when the application is running. One of these controls (dlgOpen) is a dialog form control used to open files. When we caused the Click event on the Open Note button, the application displayed this dialog window. Notice this is the same dialog you see in every Microsoft Windows Form application (Word, Excel, Access, PowerPoint) when opening files. As such, it is called a common dialog control. Visual Basic Express has an entire suite of such controls: dialogs to open files (seen here), save files (we will see soon), choose fonts, choose colors and control printing jobs. Use of these dialog controls in your Windows Form applications gives them a real professional appearance and they are familiar to your users. They also make your programming life a lot easier by providing powerful functionality to your applications. Common dialog controls are selected from the toolbox like all other controls. You can find a list of them under the Dialogs category:

Bb297400.23bf8f28-0462-40ea-bf49-b3b9f21c1e09(en-US,VS.80).png

The Hidden Note application can open any text file (.txt extension), like files created with the Windows Notepad (another Windows Form application by the way). The difference between Notepad and our Hidden Note Windows Form application is that Hidden Note can open files that have been ‘encrypted’. In the Hidden Note folder is an example encrypted file, named sample.txt. Select that file and click Open in the dialog control. The Password form we examined earlier should appear:

Bb297400.dede9a2a-6e60-4cec-b356-c9825e80bdbc(en-US,VS.80).png

Since this is an encrypted file, a password is needed to open it. The stored password is the word ‘hidden’. Type the password (note the asterisks masking the password), then click the button marked OK (causing a Click event). If you want the computer to remember the password (meaning, you only have to enter it once each time you run the application), put a check mark in the box next to Remember Password before clicking OK.

The password dialog should disappear and the contents of the decrypted file will appear:

Bb297400.fd7d84a2-f4d9-4a3b-a92a-cdc25d209094(en-US,VS.80).png

How do you know the Hidden Note program did anything with the file it just opened? Open the file (sample.txt) in Windows Notepad to see it in its encrypted form:

Bb297400.30c16cd5-72a3-4483-ab67-8e57443aa7ba(en-US,VS.80).png

The first line (“Hidden Note File”) is used by the Hidden Note program to indicate it is an encrypted file. The remainder is the actual text file. I think you can see this would be hard for someone to decipher. So, the Hidden Note program does a nifty little trick.

We’ve seen how to open a file in the Hidden Note program. Other tool bar buttons allow erasing of the displayed text, saving the text in a file and stopping the program. Play around with the program and try out these other features. Operation is pretty straightforward.

At this point, we know that a project is made up of forms and controls that let the user provide and receive information to and from the computer. Properties describe the appearance of controls. By causing events with these controls, the computer application knows when to respond and generate the desired results. Next, we’ll look at the details of how a Windows Forms application is structured. To do this, we need to stop the project.

Stopping the Sample Visual Basic Express Project

There are many ways to stop a Visual Basic Express project. We will use the toolbar in Visual Basic Express. Look for a button that looks like the Stop button on a VCR, CD player, or cassette tape player (you may have to move the project form down a bit on the screen to see the toolbar):

Bb297400.7ec4d996-8411-4618-8e54-94a3e01e3911(en-US,VS.80).png

  • Click on this button (you may have to click it twice). The project will stop and Visual Basic Express will return to design mode.

Alternate ways to stop a project are:

  • Selecting the Debug menu heading, then clicking Stop Debugging

  • Click the Close button found on the Windows form application itself. It is the little button that looks like an X in the upper right corner of the form.

Event Procedures

In the Hidden Note program, we see that by interacting with the controls (typing text, clicking toolbar buttons, typing passwords, choosing different options), we make things happen by generating control events. We say that Visual Basic is an event-driven language and is governed by an event processor. Once an event is detected, the project finds a series of instructions related to that event, called an event procedure. That procedure is executed, then program control is returned to the event processor:

Bb297400.da7459fb-4e97-44af-aa73-39dd10eb2afd(en-US,VS.80).png

Event procedures associated with various controls are where we do actual computer programming. These procedures are where we write Visual Basic language statements. In this lesson, we won’t do any coding of the Visual Basic language ourselves, but we will look at some event procedures, get a feel for the language syntax, and see it’s pretty easy to get a feeling for what happens in these procedures.

Event procedures are viewed in the Code Window. There are many ways to display the code window. First, select the desired form in the Solution Explorer window. Then, use the View Code button found in the Solution Explorer window. Or, click View on the main menu, then Code. Or, as an alternate, press the F7 function key.

Bb297400.2888c61c-e39a-4104-a455-ed8a8d16bda7(en-US,VS.80).png
Bb297400.7a7810c8-77a4-4a09-a5c7-c73ad161cbd9(en-US,VS.80).png

Each form in a project has its own code window. Find the code window for the HiddenNote form. It will appear in the main window under the HiddenNote.vb tab:

Bb297400.2f928ede-2589-455a-9960-5846a59451e4(en-US,VS.80).png

At the top of the code window are two boxes, the object (or control) list and the procedure list. The object list lists all objects on the form by name. Once an object, or control, name is selected in that list, the procedure list shows all possible event procedures for that control.

Click on the drop-down arrow in the objects list. Select tbrOpen as the object. tbrOpen is the ToolStripButton control that will open a file if it’s clicked. Select Click as the procedure. You should see this:

Bb297400.7098b91a-4fb2-4ad7-a3ca-acd45f4f0604(en-US,VS.80).png

Displayed is the Click event procedure for the control name tbrOpen (the procedure is named tbrOpen_Click). This is the code executed when a user clicks the toolbar button to open a note. And even though you may not know any Visual Basic right now, you should be able to figure out what is going on here. The first thing you should know is that any line beginning with a single apostrophe (‘) in green is a comment that gives some information as to what the following line of code is doing. The steps for this event procedure are:

  1. Display the open file dialog box

  2. If the user clicks OK, get a filename for the input file and complete the procedure. If user doesn’t click OK, leave procedure.

  3. Read the first line of the file.

  4. If the first line says ‘Hidden Note File’ (recall we put this at the top of encrypted files), then it is an encrypted file. If not, then just open as a normal text file.

  5. If it’s an encrypted file, display the Password form and make sure the correct password is entered or the user has checked the Remember Password check box (chkRemember) on the Password form (frmPassword).

  6. If the correct password has been entered, decrypt the file (using the ShiftText function) and place the results in the text box property of the text box control (txtNote.Text) on the form.

  7. When done, close the input file.

Take a look at the tbrSave_Click event procedure (the code executed when the user wants to save a note):

Bb297400.6be867b1-e7bb-4b3a-89ea-76e9ef971bfa(en-US,VS.80).png

The steps followed here are:

  1. Display the save file dialog box.

  2. If user clicks OK, get a name for the output file. If user does not click OK, leave the procedure.

  3. Write the first line of the file so we know it is encrypted.

  4. Encrypt the contents of the text box control (txtNote.Text) using the ShiftText function and place the results in the output file.

  5. When done, close the output file.

Take a look at the other event procedures for the HiddenNote form (tbrErase_Click, tbrStop_Click, frmNote_Closing). Each one of these procedures is pretty easy to understand, even without a lot of programming knowledge. There is one other procedure in the code window that is not an event procedure. This procedure is the ShiftText function used to encrypt/decrypt the contents of the text box control. To see this function, select frmNote in the object list of the code window and choose ShiftText in the procedure list:

Bb297400.a8a29586-b6b2-4f00-89e4-ee04fc8b6784(en-US,VS.80).png

So, how does this work? The text to be encrypted or decrypted (the text from the text box control) is contained in the variable named TextIn. For the encryption, it looks at each letter in that variable and shifts it one position to the left (the Direction variable is -1). In other words, an ‘e’ becomes a ‘d’, an ‘R’ becomes a ‘Q’ and so on. It’s a simple encryption scheme, but effective – recall the sample.txt file looks very confusing. With such an encryption, the word ‘Microsoft’ becomes ‘Lhbqnrnes’. To decrypt a text variable, the letters are simply shifted one position to the right (the Direction variable is +1). The code to do this encryption and decryption uses some Visual Basic functions you may not be familiar with, like ‘Asc’ or ‘Mid’, but the logic is straightforward. If you would like to learn more about these functions, you can right-click on them and select ‘Go to Definition’ to get a more detailed explanation of what these do:

Bb297400.f20702d8-a181-4b4e-a2af-b8c749f65dbf(en-US,VS.80).png

The Password form has event procedures you can also examine. To view its code window, select the Password form in the Solution Explorer window, then open the code window using one of the previously described methods. The code is displayed on the Password.vb tab:

Bb297400.deac4001-5cb9-49c9-af25-319e34b57e8f(en-US,VS.80).png

The frmPassword_Load event procedure is executed when the form is first opened (it clears the password text box). The btnOK_Click procedure is executed when the user clicks the OK button. This procedure checks to see if the password is correct (the correct password is stored at the top of the code window in the constant variable MyPassword and its value is the text “hidden”). The txtPassword_KeyPress event is executed whenever a key is pressed in the password text box (txtPassword). In this code, we check to see if the user pressed the <Enter> key (represented by ControlChars.Cr). If so, we simulate a click on the OK button. Again, you should see that the code written here is fairly easy to understand.

What Now?

In this lesson on Windows Forms applications, we looked at an example project (Hidden Note) and learned the important parts of such a project and how these parts work together. We learned that projects are built on forms. Forms use controls to gather information from a user and to provide feedback to a user. The properties of these controls govern their appearance on the form. We learned that Visual Basic is an event-driven language. This means when a user interacts with a control, an event is generated. Once an event occurs, the code (written using the Visual Basic language) residing in the corresponding event procedure is executed. So, now what should you do with all this new information?

Customizing the Windows Form application

After learning more Visual Basic and more about the development environment (including controls, properties, events), you might like to add more features to the Hidden Note application. Here are some of my ideas – I’m sure you have your own:

  • Use graphics and colors to make the interface a little ‘prettier’

  • Add simple formatting features to the text box – change font name, font size, font type

  • Add ‘selective’ formatting by replacing the text box control with a rich text box control

  • Add simple menus to the application

  • Add printing capabilities to the application

  • Research and implement other encryption possibilities.

Change the secret password from “hidden” to something else

Learning More

Hopefully, this lesson has whetted your appetite to learn more about Visual Basic Express Windows Forms applications. You may already have some ideas about applications you would like to build. There is a wealth of material out there to help you gain the knowledge you need to start building your own projects. The bookstores have many books to help you along. The Internet is full of self-help tutorials. There is no lack of learning material. Our company, KIDware, offers two particular tutorials that you may find useful.

Our first tutorial is entitled Beginning Visual Basic Express. This tutorial is written for the absolute beginner - no programming experience is required, but familiarity with Windows use is expected. The tutorial is presented using a combination of over 400 pages of course notes and actual Visual Basic Express examples. Ten "plain-English" lessons explain the Visual Basic Express toolbox, event methods, and many elements of the BASIC computer language. Examples are used to demonstrate every step in the application building process. The tutorial also includes several computer projects that illustrate practical applications of Visual Basic Express, including loan calculators, graphics programs, portfolio managers, checkbook balancers, and even a simple video game! Further details can be found at:

http://www.kidwaresoftware.com/beginvbe.htm

If you’re fairly competent with Visual Basic Express, our second tutorial, Home Projects With Visual Basic Express, is for you. This tutorial explains (in simple, easy-to-follow terms) how to build a Visual Basic Express Windows Forms project. You learn about project design, the Visual Basic Express toolbox, many elements of the Visual Basic language, and how to debug and distribute finished projects. The projects built include:

  • Dual-Mode Stopwatch - Allows you to time tasks you may be doing.

  • Consumer Loan Assistant - Helps you see just how much those credit cards are costing you.

  • Flash Card Math Quiz - Lets you practice basic addition, subtraction, multiplication and division skills.

  • Multiple Choice Exam - Quizzes a user on matching pairs of items, like countries/capitals, words/meanings, books/authors.

  • Blackjack Card Game - Play the classic casino card game against the computer.

  • Biorhythm Tracker - Discover your physical, emotional and intellectual cycles for any day you choose.

  • Weight Monitor - Track your weight each day and monitor your progress toward established goals.

  • Home Inventory Manager - Helps you keep track of all your belongings - even includes photographs.

  • Snowball Toss Game - Lets you throw snowballs at another player or against the computer - has varying difficulties.

The product includes over 700 pages of self-study notes, all Visual Basic Express source code and all needed graphics and sound files. Further details can be found at:

http://www.kidwaresoftware.com/buildvbe.htm

Thanks for reading through this brief lesson. We hope it’s given you an idea of the power behind Visual Basic Express and how it can be used to build commercial quality, full-featured Windows Forms applications.