Visible Results With Visual Basic

Al built this Windows 3 network e-mail system with just 640 lines of code in only four days using Microsoft's Visual Basic.


December 01, 1991
URL:http://www.drdobbs.com/windows/visible-results-with-visual-basic/184408673

Figure 1


Copyright © 1991, Dr. Dobb's Journal

Figure 2


Copyright © 1991, Dr. Dobb's Journal

Figure 3


Copyright © 1991, Dr. Dobb's Journal

DEC91: VISIBLE RESULTS WITH VISUAL BASIC

VISIBLE RESULTS WITH VISUAL BASIC

Building a network mail application--in four days!

This article contains the following executables: EMAIL.ARC

Al Stevens

Al is a DDJ contributing editor and can be contacted at 501 Galveston Dr., Redwood City, CA 94063.


A small revolution is quietly taking place in the world of the Windows/DOS programmer. Microsoft has flattened the Windows programming ramp into a gentle slope with a product called Visual Basic, a program development environment that makes Windows programming not only a breeze, but a pleasure as well.

Visual Basic is a milestone product that defines the next generation for desktop software development. It integrates the interactive design of the application's user interface with Basic language code that processes the user's actions. A programmer designs screen windows and dialog boxes by using onscreen, interactive tools and integrates this visual design with fragments of code to create a Windows application. What is so important about this integration?

A large part of the development of most interactive programs is the design and implementation of the user interface. The Windows API provides hooks into the function libraries that display windows and collect the user's actions. Using that API, however, is not easy, particularly if you are new to Windows. It takes some time for a newcomer to climb the learning ramp. The Software Development Kit (SDK) has a lot of functions and tools for the programmer to learn -- more than most programmers care to tackle. Once you have all the functions, messages, resources, and so on under your belt, you write code--a lot of code -- to display and manage windows, menus, and dialog boxes. Most of your work is involved with user interface code.

Writing a Windows program is an iterative process of designing the user interface, writing the code, compiling, testing, and changing your mind about what looks good. Visual Basic does not eliminate the iterations, but it assumes most of the tedium. It targets the tasks that occupy most of a programmer's time and greases the two toughest parts of Windows programming -- designing the interface and writing the code to support it. There are no longer any valid reasons why a programmer should be unable or unwilling to write Windows programs.

Visual Basic is not the first developer's tool to integrate design and coding, but it will score more impact on the programming community, first because it comes from Microsoft, but more importantly because it supports Windows programming. Its origins at Microsoft virtually guarantee that it will be aggressively promoted and supported. Its support of Windows opens a flood gate for new applications that were not developed before because Windows programming was too difficult. Visual Basic might not be the tool to build the next horizontal "killer app," but it is more than sufficient for all those custom and vertical applications that have gone begging because nobody wanted to jump feet-first into the SDK quagmire. We have come to believe that Windows programming is too difficult for the average programmer, giving rise to a Windows programming priesthood. That perception is wrong, but until now becoming a productive Windows programmer required a significant investment in time.

The example electronic mail program that accompanies this article is my first Windows application of any significance whatsoever. There are only about 640 lines of code in the program, and it took about four days to write. That included learning Visual Basic, relearning the fundamentals of the Basic language, learning something more about Windows programming, designing the program and its data structures, and, oh yes, writing the code. More about the mail program later.

Designing the User Interface

You write Visual Basic programs by interactively building the screen windows the user will see and adding the code that processes the user's actions. Each window is called a "form" in Visual Basic. When you start Visual Basic, you see a typical Windows menu bar across the top, a collection of tool icons down the left edge of the screen, a project window on the right, and a big fat blank form in the middle. The project window lists elements of the program. At first, there are two items in the list -- the form and an empty file called GLOBAL.BAS. The form represents the first thing the user will deal with when your program starts.

You write your program by changing the form's appearance and adding visual components, and code to it. This process involves changing the form's size and position and adding "controls" and menus. Controls are text-entry boxes, check boxes, radio and command buttons, scroll bars, list boxes, labels, and so on all typical of Windows applications. Visual Basic groups these forms and controls into "objects." Besides the usual controls, there are specialized drive, directory, and list boxes that navigate the disk and file system, display the current values, and let the user change them. The Picture is another control type. It lets you include bitmap images in your application. You can add the images when you design the application and you can load them at runtime from bitmap and icon files. Visual Basic comes with a collection of canned icon files. One of its sample applications is an icon editor and viewer program, so you can build your own icons from scratch or modify one of the canned ones. You can draw pictures at runtime as well by using the Visual Basic graphics commands. There is a Timer control, too, into which you build the code that executes after specified time-outs.

To add a control to a form during design, you select its icon from the tool box and position the control on the form, using the mouse to drag the control around and fix its size. Each object has a unique control identifier that the program uses to address the control. Objects have properties that describe their appearance and behavior. You determine some of the properties when you design the program, and you can change some of them at runtime from within the code. Among the form's properties are its form name, which the program uses to address the form; its caption, which appears in the title bar; whether it has a control box and minimize and maximize buttons; what the mouse cursor looks like; the form's color; its border style; whether the user can change its size; and so on. Controls have properties relevant to their type. A text box might have scroll bars, for example, and it can use any of several fonts and font sizes. A check box might be initially checked or unchecked. You can organize controls into groups, too, which affects how the user addresses them, and you can define the order that the user tabs among the controls.

A menu is a menu bar with pull-down menus, typical in Windows applications. To build it, you open the Menu Design Window and define each item on the menu bar and each item in the pull-down menus in an outline-style indentured table. You must specify a control name for each selection as well as other menu properties, such as whether the selection is checked, enabled, or visible when the menu first displays. You can assign shortcut and accelerator keys to the menu selections.

Any time during this design process you can tell Visual Basic to run your program. Even though you haven't written any code yet, the form displays just as the user will see it. You can pull down menus, tab among the controls, key in some text, turn the check boxes on and off, push the radio buttons, and so on.

Writing the Code

During the form design process, you can double-click an object and Visual Basic will open a code window for the form with the object selected. The code window has "Object" and "Proc" drop-down list boxes at the top. The Object list contains an entry for the form and one for each of the controls and menu selections that you have designed. The entries identify the items by their control names. Visual Basic assigns default names: Form1, Form2, Check1, Edit1, and so on. You soon learn to use more meaningful names. Each entry in the Object list has an associated Proc list. The Proc entries are fixed according to the type of the object. Check boxes have one set of Proc entries, list boxes have another, and so on. Each Proc entry is an event, and each event has a code fragment that the event executes. Initially, these code fragments are empty. It is your job to write the code.

Suppose that you design an application with two forms, and the first form loads the second form when the user selects a particular command button -- call it the NewForm button. You would write the code that processes the Click event for the NewForm button. Visual Basic names the subroutines by using the object name and the event. The subroutine for the Click event on your NewForm button would look like this:

  Sub NewForm_Click

  End Sub

You would put the one or two lines of code into the subroutine that loads and displays the second form. That's all there is to it. Your program is mostly a collection of small code fragments that react to events.

Besides the code fragments for events, there are places for you to put common subroutines and functions and global declarations.

The Application Definition Files

A Visual Basic application store its design in several files. The definition of each form and the code for its objects are in a module with the form's CtlName property for a filename and .FRM as the extension. The GLOBAL.BAS module has global declarations and constants. You can insert a Visual Basic file named CONSTANT.TXT into the GLOBAL.BAS module to get some standard definitions, and you put your own global definitions there as well. Most programs will have at least one other .BAS module that contains functions and subroutines that are common across forms. This collection of .BAS and .FRM modules constitutes the design and implementation of your Windows application. The modules are listed in the Project Window. The contents of the Project Window are recorded in the project's .MAK file.

Debugging

Visual Basic's debugger is a primitive one, slightly better that GWBASIC debugging techniques and almost as good as QuickBasic's Debug mode. You can set breakpoints, step through the program one statement at a time, step through procedures, and break into the program's execution. You can make source code changes, often without restarting. You can use the Immediate Window to enter and execute Basic commands while the program is interrupted, perhaps to view or change the values of variables.

Don't be put off by the shortage of debugging features. Most of the reasons why you need full-functioned debuggers in DOS do not apply to Visual Basic programs. The code that will have the bugs in it are those small event-driven modules. The logic that drives their execution is a function of your visual design rather than the structure of a program. Visual Basic manages the parts of a Windows program that usually have the difficult bugs.

The Runtime Application

To prepare your application for distribution to users, you tell Visual Basic to make the .EXE file. This file, along with the VBRUN100.DLL file supplied with Visual Basic, is all the user needs. Microsoft allows you to freely distribute the runtime DLL. No doubt future versions of Windows will include this file or one of its successors.

Distributing Source Code

If you print source code for documentation or distribution, you are in trouble. The source code is a small part of a Visual Basic application. Most of the programmer's efforts are in the design of objects, which is buried inside the .FRM files. You can print source code or save it to .TXT files. You can print mostly useless primitive line drawings that resemble your forms, but do not display everything. No matter, a screen capture to the Clipboard and a session with Windows Paint will get your screens into print.

Printing the source code and pictures of the forms is not enough, though. The glue that holds everything together is the design of the objects. Each object has an object type, a name, and properties. For example, readers of your documentation will not understand the FooBar_CLick subroutine if they do not know that FooBar is a command button, and they will not understand when another part of the program changes the property of the FooBar.Enabled property. Visual Basic provides no way for you to view these properties other than to look at them on the screen. Documentation of Visual Basic programs needs to be on magnetic media. Print the pictures and describe the more interesting code fragments, but give them the rest on a diskette.

VBMAIL: An Example

To wring out Visual Basic and get up to speed, I developed a simple electronic mail program for networks and called it VBMAIL. I'll explain the program here to give you an idea of the scope of an application that one can develop in a short time.

The VBMAIL program starts with an AddrBook form for the address book shown in Figure 1. You sign on by selecting your user name from the address book. If your name is not already in the address book, you can enter your userid and name into InputBox$ dialog boxes, and VBMAIL will add you to the book. Each user has a file named userid. USR with the user's name and a subdirectory to store mail messages and the mail database.

An environment variable such as USR=JUDY bypasses the sign-on process.

Reading and Saving Mail

After you are logged on, VBMAIL displays the MailBox form shown in Figure 2. Mail is stored in your subdirectory in files named EMAILnnn.MSG. The nnn is a number from 000 to 999. You cannot have more than 1000 messages. The mailbox displays the date, sender, and subject of each message. The text box at the bottom of the form shows the text of whichever message is currently selected in the list box. The user can scroll through the message list and the message text.

The File menu on the MailBox form lets you open an Editor form (Figure 3) to write and send mail. It also lets you open the Mail Files form to view incoming messages that you have saved. Viewing the Mail Files is the same as viewing the MailBox, except that the program displays files with the .FIL extension rather than .MSG. The Save command from the MailBox form's File menu renames the selected .MSG file to a .FIL file. The Reply command opens the Reply form initialized to reply to the selected message. The Delete command on the File menu deletes the message file after you respond to a confirmation message box. Visual Basic includes a standard set of message and string input dialog boxes that you can invoke with a single function or subroutine call.

VBMAIL includes a form named Holder that is never seen by the user. Its purpose is to host two icons for the mailbox and a timer control that watches for incoming mail so VBMAIL can alert the user.

Sending Mail

To write a new message from the Editor form, you type the message, address it, and send it. The address must be one of the user names from the Address Book. You can open the AddrBook form to retrieve a user name or type it in yourself. If you leave the name blank or type an invalid one, VBMAIL automatically opens the AddrBook form for you.

Writing a Reply is similar to writing a new message, except that the address is always the sender of the message to which you are replying, and you can read that message while you write the reply. New messages and replies are written into the receiving user's subdirectory with the .SND file extension.

Watching for Incoming Mail

The timer control in the Holder form runs every five seconds and uses the Dir$ function to see if there are any .SND files in the user's subdirectory. If so, VBMAIL changes the name of the file to .MSG so that it will not see it again, reads it, and adds it to the MailBox form's list-box control, changes the MailBox's icon from an empty mailbox with the flag down to one with a letter in it and the flag up, and alerts the user with the Beep statement. If there are no .SND files, the timer changes the icon back to the empty mailbox. Both icons come from the Visual Basic icon set.

Using the Clipboard

The Editor and Reply forms have Edit menus with Cut, Copy, Paste, and Delete commands. Visual Basic text controls already have these functions built into the Shift+Del, Ctrl+Ins, Shift+Ins, and Del accelerator keys. The code fragments for the menu selections use the SendKeys statement to execute the operations. Visual Basic takes care of the rest.

Read-Only Text Boxes

The message-reading textboxes on the MailBox and Reply forms are read-only. Visual Basic does not include a read-only property for text controls, so you must do it yourself. VBMAIL allows the user to Copy text from these read-only messages into the Clipboard, to Paste the text into replies, for example, but the user must not add or delete text in the read-only text controls. By adding code to the KeyPress and KeyDown events for these controls, I was able to head off any keystrokes that would change the text and still pass through the keys that move the cursor around, mark blocks, and copy them to the Clipboard.

Due to space limitations, the source code for the VBMAIL program is provided electronically (see "Availability," page 3). By examining the listings and looking at the figures, you can see how the program is designed.

If you are not on a network, you can run two copies of VBMAIL with different userids and send messages back and forth. If the receiver's MailBox form is minimized, you will see its icon raise its flag within five seconds from the time the sender sends a message. If the receiver's MailBox is active, you will see the message appear in the list-box control.

Improving VBMAIL

VBMAIL is a compact e-mail application. How could you improve it? First, you could combine the messages into indexed files to improve access time and disk space use. VBMAIL does not keep copies of messages that you send to other users, and that feature would be an improvement. You could add message threads, text searches, multiple database folders, and private address books. VBMAIL could copy messages to one or more carbon copy receivers. How about blind carbon copies? Distribution lists? Enclosures? You could add gateways to delivery agents, such as MHS, and to other mail systems, such as CompuServe and MCI Mail. You might want to rearrange the users' subdirectory structure to use network protection strategies so that users could not read or delete one another's mail.

Despite these potential improvements, VBMAIL is a significant application for a four-day project with only 640 lines of code to debug. The design phase of the project took no more -- probably much less -- time than it would have taken if I had written VBMAIL in C and used the SDK. After a design is done with the SDK, I have to code all those window-processing modules with all those switch statements and all those bugs -- all the time with my head buried in the Windows Programmer's Reference to keep track of the hundreds of API functions and messages.

What do You Need to Know?

To use Visual Basic, you need to know what Windows programs look like. You'll get that exposure by installing Windows and playing with the accessory programs. You need to understand event-driven programming. That will come naturally. There is no other way to write a Visual Basic program, and learning event-driven techniques will be a side-effect of your first development task.

It will be helpful to have and know how to read the Windows Programmer's Reference. From time to time you will want to do something that Visual Basic does not support, and you might be able to do it with the Windows API. You can get the Programmer's Reference at the book store. Microsoft Press publishes it as a book.

Finally, you will need to know or learn the QuickBasic dialect of Basic. More about that later.

Problems

Visual Basic is a well-conceived, well-implemented product, particularly for version 1, and more particularly for such a radically different product. It has its problems and its deficiencies, but most of these have workarounds. Where there are no workarounds, one learns to do without or be careful. Here are some of the knots I hit.

If you accidentally bump the Del key while you have a control selected, Visual Basic deletes the control. The Undo command on the Edit menu does nothing following such a deletion. You have to rebuild the control from scratch. Visual Basic does save the deleted object's code fragments in the Proc list of the form's General object, but the visual part of the control is gone. If you delete a frame that contains several other controls, you've just lost a lot of work. At the very least, Visual Basic should ask you to confirm the deletion.

The Color Palette has a number of nonsolid colors, and you can build custom colors. These colors can be the background of a control. But when that control is a label, the background of the character boxes is always the solid component of the color. The workaround is to use the PRINT statement to create labels on a form, but then you cannot get Click events for the pseudolabels.

If you make changes to your forms and delete controls, Visual Basic keeps some residue in its form definition files. The compiled .EXE file is bigger than it needs to be. To get the smallest .EXE size, you must save the source code as text and then load it back in, replacing the original code. Then, immediately build your .EXE. I saw VBMAIL.EXE shrink by 3K after one such session.

For some reason, the Save Text command on the Code module sometimes defaults to the subdirectory for icons rather than the subdirectory of the .FRM or .BAS file. I went through several Saves and Loads before I realized I wasn't getting anywhere.

When you start a Windows program from the Program Manager, Windows sets the startup subdirectory to where the .EXE file is. When you run a program from within the Visual Basic design process, there is no way to tell it where you want the current subdirectory to be. For this reason, programs that look for subdirectories below their own path will need a ChDir in the start-up code just for testing within Visual Basic. VBMAIL has such a statement in its Main function. You'll need to take that statement out before you build the .EXE file.

So far, I've had only two of the dreaded and infamous Windows Unrecoverable Application Errors (UAE) while running Visual Basic. I don't know how I got the first one, and I could not reproduce it, but it cost me about an hour's work. I save my work more often now. The other UAE came when I tried to merge all of a big Microsoft file named WINAPI.TXT into the GLOBAL.BAS file. From that point on, Visual Basic reported that it was out of memory, no matter what I did to clean things up. After a while I got the UAE. UAEs are a fact of life among Windows programmers. Unfortunately, Windows users see them as well, all too often, Microsoft should install UAE-activated cattle prods into its programmers' chairs. They'd work harder to make Windows more reliable.

How Good is Basic?

Basic bashing is probably more popular than C bashing, mainly because most C programmers do it, and they (we) seem to outnumber everybody else. If anything will keep programmers away from Visual Basic, it will be the "Basic" part. Visions of line numbers, GOTOs, no local scope, no structure, all bring to mind the Basic of yore. Visual Basic is not the same Basic that some of us remember. It is a dialect of QuickBasic with most of the structured programming constructs that a programmer needs. The language is effective, robust, and complete.

There is one insidious feature that has been in Basic from its beginnings, and Visual Basic has it too. A program can implicitly declare variables by referencing them. The compiler sees a new variable name and declares it with whatever type the code expects. Visual Basic supports explicit declarations of local and global variables, but the old way works, too, automatically declaring variables that you do not explicitly declare elsewhere. Misspell a variable name and you declare a new variable, like it or not. You can do a lot of head scratching when the program acts up. Other than for that, I don't see much wrong with the Visual Basic version of the Basic language.

The Windows API

Eventually, you will hit the limit with Visual Basic. You will want to do something that you know other Windows programs can do but that Visual Basic does not support. Inasmuch as Visual Basic programs run in the Windows operating environment, most of the function calls of the Windows API are available to the program, and there is a good chance that you can do what you want.

WINAPI.TXT is a file that declares the functions for the Windows API. You have to get that file from Microsoft. (It is on CompuServe in the MSLANG libraries.) To use the file, you must determine which API functions you need and put those declarations into GLOBAL.BAS. With the API declarations in GLOBAL.BAS, you can call the Windows API functions from your Basic code by using the subroutine calling conventions.

Add-ons

Visual Basic does not have everything. For example, it does not support the Multiple Document Interface or multiple-line selection list boxes. You'll need to look for add-on libraries of Visual Basic tools from other vendors if you need these features. As programmers dream up things they'd like to have, somebody builds the add-ons. You can add custom DLLs, controls, and reusable forms to your application. There are several third party vendors providing such add-ons, and the list of vendors and products is growing. There are already Visual Basic add-ons for database engines, communications drivers, and interfaces to network APIs.

Not every application will use only the small set of controls that Visual Basic includes. Some vendors sell add-on tools that implement new controls. Visual Basic accepts .VBX files that describe a control with its format and properties. When you add such a file to an application, Visual Basic integrates the control's icon into the Toolbox window, and you can add the control to the forms in your application. You can also incorporate other Visual Basic source files into your programs. For example, code for the Windows standard File Open and Save dialog boxes is available.

Products Mentioned

Visual Basic Microsoft Corporation One Microsoft Way Redmond, WA 98052-6399 206-882-8080 $199 Minimum requirements: 80286, DOS 3.1, Windows 3.0, 1 Mbyte RAM, CGA display, hard disk, and a Microsoft-compatible mouse

The Visual Change of Life?

Programmers and reviewers have been rhapsodizing for several months about Visual Basic, suggesting that it has changed their lives forever. To a certain extent -- not including forever -- this can be true. I cannot promise what it will do for you, but I can offer some guesses from my own experience. For one thing, I spend more time in Windows than ever before. And, for the first time in years, I am writing programs in something other than C. But these are personal experiences. How will Visual Basic change the world of programming as a whole?

First, Visual Basic will do more toward legitimatizing Windows as the dominant GUI -- perhaps the dominant UI -- than anything else Microsoft has tried, simply because it hurls open the doors for the development of Windows programs. It would seem that Visual Basic is as much a Microsoft marketing ploy to entrench Windows as it is to cut another notch in the language market. No matter, all to the good. There will be more public domain, shareware, and commercial software for Windows than ever before -- not only developer's add-on tools, but applications, too. The increase in Windows applications will increase the acceptance of Windows by users, which will create a demand for more applications, thereby creating opportunities for Windows programmers.

Second, Visual Basic does for Windows programming what dBase did for DOS applications development -- it puts the technology within easy reach of more programmers. You do not have to be a technical wizard to write Windows programs any more. You might hear that Visual Basic is everyman's programming tool. Not so. You still need to know how to write a program. Nonetheless, the Windows priesthood is, it seems, finally where it belongs -- snapping at the heels of the snail darter, the eight-inch floppy disk, and the Communist Party. There will be more Windows programmers now than ever before.

Third, the success of Visual Basic -- which I predict will be substantial -- redefines how programming is done. There will be an outpouring of similar visual language products with other languages and for other platforms, and that is good for all of us.


Copyright © 1991, Dr. Dobb's Journal

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.