Visual Development and Event-Driven Programming VB Help

Forms and controls are the basic elements in the user interface of any .windows application. in V Basic, these elements are called objects because they are manipulated like objects. Objects have properties and methods, and they read to external events, as does any physical object. Your car, for example. is a physical object, and one of.its properties is color. Normally. properties due set when an object is created. If you don’t like the color of the car are you ordered It, you can still change it. Most control properties are set when the object is created (placed on the Form), but you can change a property later by assigning a new value to it. You can change a property at design time (through the Properties window) or-at runtime (through your code).

Visual Basic assigns default properties fa every new control you place on a Form. The default Name property, for example, is the name of the control, followed by a number (Commandl, Command2, and so on). The background color of must controls is either gray or white. You can examine the property values of a newly created control in the Properties window.

A few properties are available only at design time, and some others are available only at runtime. You can’t specify an item in a ListBox control at design -time because the control is empty. It is populated with Visual Basic statements ”’when the program starts. (It is also possible to pre-populate the control at design time by assigning values to the List property, but the actual handling of the control’s items takes place at runtime.) The Text property of the ListBox control, therefore, has no meaning at design time. At runtime, it is the control’s most important property.

The MultiLine property of the TextBox control, on the other hand, determines whether the textbox holds multiple lines of text. You can set this property only at . design time, and it can’t be changed at runtime.

Some properties are only available at runtime and are read-only, for example, the number of items in a ListBox control. You can only find out the number of items in the control. To change their count, you must either add or remove items.

A Few Common Properties

The following properties apply to most objects.

Name This property sets the name of the control, through which you can access the control’s properties and methods.

Appearance This property can be 0 for a-flat look or 1 for a 3-D look. The examples in this book use the 3-D look for most controls.

BackColor This property sets the background color on which text is displayed or graphics are drawn.

ForeColor This property sets the foreground color (pen color or text color).

Font This property sets the face, attribute, and size of the font used for the text on the control (text in a TextBox control, the caption of a label or Command button, and so on).

Caption This property sets the text that is displayed on many controls that don’t accept input, for example, the text on a Label control, the caption of a Command button control, and the strings displayed next to the CheckBox and Option button controls.

Text This property sets the text that is displayed on the controls that accept user input, for example, the Textix» control. Some other controls that can accept text, such as the RichTextBox control, don’t appear by default in the Toolbox.

Width, Height These properties set the control’s dimensions. Usually, the dimensions of a control are determined with the visual tools we have explored already. But you can read the control’s dimensions or set them from within your code with these properties. The default units are twips, and there are 1,44.0 twips in an inch .

Left, Top These properties set the coordinates of the control’s upper-left comer, expressed in the units of the container (usually a Form). The placement of a control on the Form can be specified with the Form Layout window, but you can change it from within your code with these two properties. The default units are twips.

Enabled By default, this property’s value is True, which means that the control can get the focus. Set it to False to disable the control. A disabled control appears gray and can’t accept user input.

Visible Set this property to False to make a control invisible. Sometimes, you use invisible controls to store information that is used internally by the application and should not be seen or manipulated by the user.

A Few Common Methods

Objects have methods too, which are the actions they can carry out. You can think of methods as the actions of an object. For example, the methods of your VCR are the Play, Fast Forward, Rewind, Pause, and Record buttons. After you press one of these buttons, your VCR can perform without any further assistance from you. The Form object, for example, knows ho w to clear itself, and you can invoke the Cls method to dear a Form. A Form also knows how to hide itself, an action that you can invoke from within your code with the Hide method.


Some methods are simple verbs that tell the object the action to carry out. The Clear method tells the control to discard its contents. If the object is a ListBox, the Clear method removes all its item from the control. The Clear method can also be applied to the Slipboard object, to clear its contents

Move All controls that are visible at runtime (only the Timer control is invisible . at runtime) provide a Move method that lets you move and resize them from within your application’s code. The syntax of the Move method is:

Control.Move left. top, width, height

Control is a control’s name’ (like Commandl or Textl).; left and top are the coordinates of the upper-left comer of the control’s new position, and width and height are the control’s new dimensions. Use the Move method to resize and reposition a control at once at runtime. For more information on coordinates.

Addltem, Removeltem These methods are used to manipulate the items in a ListBox or ComboBox control. The application doesn’t have to know how the items are stored in the control. It issues the AddItem method, and the control takes care of appending or inserting the new item in the list. And this is exactly why methods are used. They are the actions each control can perform without any assistance from the programmer. In effect, methods hide the implementation details of the controls’ features, and the programmer can exploit these features by calling a method, which is
similar to setting a property value.

For example, to add the item “Canada” in the Listbox control named Countries (which presumably maintains a list of countries), use the following statement:

Countries.Addltem ‘Canada’

The ListBox control appends the string “Canad .1” at the end of the list. If the list is sorted (its Sorted property was set to True at design time), the new item is inserted in the proper order in the list. The Addltem method does a good deal of work behind the scenes, but as a programmer, you needn’t worry about the details. All you need to know is the name of the method.

As you can see, to apply a method to a control, you specify the name of the control followed by a period and then the name of the method. The syntax is nearly identical to the syntax of properties. The difference is that a method isn’t assigned value. Typically, a method accepts one or more parameters that tell it exactly how to perform an action.

Some methods, such as the Clear method, are quite simple. You merely specify , , the name of the control it applies to and the method’s name. Some others require additional information. The Addltem method, for instance, which adds a new item to a ListBox control, must know the item to ado. When you call this method, you must also supply the value of the item to be added to the list, as you saw in the previous example.

The PictureBox control provides a method for drawing lines. For the PictureBox control to draw a line, it must know the end coordinates of the line (line drawing and other drawing methods are explained).

A Few Common Events

Events determine the control’s reactions to external conditions. Controls recognize events, but your application handles them. A Command button will recognize that it was clicked.but it won’t react to the event unless you provide some code. In other words, you must tell Visual Basic what to do when the user clicks the specific ,Command button, as we did in the second example in this chapter. Once you specify a subroutine for the control’s Click event, this subroutine executes each time the control is clicked. The subroutine that determines how a control reacts to an event .AI
is called an event handler.

To write an event handler for a control, follow these steps:

1. Switch to the Code window, or double-click the control for which you want to write the event handler.
2. At the top of the Code window, which is shown, you will see two drop-down lists. The first contains the names of all the controls on the Form. Select the control for which you want to write an event handler. The second list contains all the events the selected control can recognize. Select the event for which you want to write an event handler.

The combination of the control’s name and the event’s name is unique and is the . name of the event handler. Each time an event takes place, Visual Basic looks for the subroutine made up of the name of the control on which the event took place and the name of the event. If such a handler exists, it’s executed. If not, your application won’t react to the event. (Typically, applications react to a small number of events.)

The two most. common groups of events are mouse (events caused with the mouse) and keyboard (events caused with the keyboard).

FIGURE 1.18:

Mouse Events

The events triggered by mouse actions are the most common events in programming with Visual Basil’. Most of the elements of the user interface can be manipulated with the mouse, and programming mouse events is your number one job as a VB programmer. However, many users prefer the keyboard, even for operations that are simpler to carry out with the mouse, so you must not favor mouse operations to the exclusion of their keyboard equivalents.

Click. DblClick

The Click event takes place when the user clicks the left mouse button; the DblClick event takes place when the user double-clicks the left mouse button.

MouseDown, MouseUp

The MouseDown event when the mouse button is pressed, and the MouseUp event takes place as it is released.


This event takes place continuously as the mouse is moved over a-control, The order in which mouse events take-place is as follows:

1. As the mouse is moved around, the MouseMove event is triggered continuously,
2. When the ‘user presses a mouse button, the MouseDown event is triggered.
3. If the user continues to move the mouse’ around while holding down the button, the program keeps receiving MouseMove events.
4. When the user releases the mouse button, the MouseUp event is triggered.
5. . If the left mouse button was held down, the Click event is triggered immediately after the MouseUp event.

When the mouse button is double-clicked, the following events take place in the order listed: MouseDown, MouseUp, Click, Double-Click, and MouseUp.

It’s a bit involved, but there will never be a reason to program all mouse events or the same control (unless you want to find out the order in which the events are received).

The mouse events you’ll be ‘using most often are the Click and DblClick events. If you want finer control of the mouse actions, you will have to program the Mouse- Down and MouseUp events. For example, if you want to know the coordinates ‘of the point where the mouse was clicked, you will use the MouseDown and MouseUp events. The definitions of the Click and DblClick events are as follows:


The Button argument reports which mouse button caused the event. The Shift argument reports the status of the Shift, Ctrl, and Alt keys; and the X and Y arguments arc the coordinates of the point where the mouse button was released.



To find out which button caused the MouseDown or MouseUp event, use the following If structure:

If Button = vbLeftButton ‘Then
{process left button}
End If

You can write a mouse handler to simulate the double-click with the click of the middle mouse button (this will work with three-button mice only, but won’t aff the operation of a two-button mouse). ‘Insert the following lines in the Mousel.Ip event handler:


This event handler monitors the MouseUp event for the middle button, and when detects the event, it invokes the Form_DblClick event handler. Notice that although you can’t cause the DblClick event from within your code, you can call the even’ handler.

Similarly, you can detect the state of the Shift key while the mouse button . pressed. Suppose you want to perform one action when the Command 1.

clicked and a different action when the same control is clicked with the Ctrl key pressed. To do so, test the Shift argument with an If structure like the following:

If Shift – vbCtrlMask Then
{Mouse was pressed while Control key down}
End If

Keyboard Events

Keyboard events are generated by keystrokes. Usually, you must program the keyboard events for the controls that can accept text. In addition, you must provide code for the keyboard events of controls that can be manipulated with both the mouse and the keyboard, because many users prefer to work with the keyboard most of the time,

KeyDown, KeyUp The KeyDown event is triggered when a key is pressed, and the KeyUp event is triggered when a key is released.

KeyPress In practice, your code doesn’t care about the KeyDown and KeyUp events. Most programs use the KeyPress event to find out which key was pressed. The KeyPress event is used frequently to write keyboard handlers for textboxes, because this event takes place before the character pressed is displayed in the textbox. The definition of the KeyPress event is:

Private Sub Textl_KeyPress(KeyAscii As Integer)
End Sub

The KeyAscii argument is’the ASCII character of the key pressed. You can use this event to even reject the character typed. Setting the KeyAscii argument to 0 in effect chokes the keystroke, and the control never sees it. The character that corresponds to this ASCII code is:


The ASCII codes of the numeric digits start at 48 (for the digit 0) and end at 57 (for the digit 9). The following event handler allows the user to enter only numeric digits in the Textl textbox:


Change The Change event is triggered by various controls when their contents change. The Change event is generated for the TextBox control each time a new character is typed or deleted. It is generated for the CheckBox control every time the user change~ its status by clicking it.

Most Windows applications prompt you to save your data when it has been changed since the last Save operation. You can easily add this feature to your applications by setting a variable from within the Change event. When the user saves the contents of a textbox, reset this variable to indicate that the user can quit the application without saving the control’s contents. If the user types even a single character after saving the me, the variable is set from within the Change event to indicate that the text has been changed and that the application should prompt the user before exiting.

VB6 at Work: The Focus Project

The Focus application, which you will find in the FOCUS folder on the CD, has five single-line textboxes in which the user can enter data. Every time the user presses Enter, the focus moves to the next control. To capture the Enter key, you use the KeyUp event, which reports the code of the key pressed.


The other textboxes have similar event handlers for the KeyUp event. When the user presses Enter while the last textbox has the focus, the focus moves to the Save Record Command button, as follows:


·This button doesn’t save tile data anywhere. It simply displays a message, clears the textboxes, and then moves the focus to the first textbox. ,


Tab Order

All Windows applications allow the user to move the focus from one control to an other with the Tab key. For this to happen, you must decide how the focus is moved from one control to the other. In other words, you must decide which control gets the focus each time the user presses Tab. This is known as Tab order. Each control has its own Tab order, which is by default the order in which the controls were created.

Because controls are rarely placed on a Form in the same order they will be used, you need to be abfeto change the Tab order. You do so with the Tablndex property, which determines the control’s position in the Tab order. The first control that is drawn has a TabIndex value of 0, the second has a TabIndex of 1,and so on. The focus is moved from each control to the one with the next TabIndex value. To change the order in which the focus moves from one control to another, you change the TabIndex property of the control. When the Tab order for a given control is changed, VIsual , Basicautomaticallyrenumbers the Tab order of the remaining controls on the Form to reflect insertions and deletions.

If you don’t want the user to move to a specific control, you can remove it from the Tab order by setting its TabStop property to False. The TabStqp property deter- . mines whether the control can get the focus, but does not determine ,its Tab order: Regardless of the setting of the TabStop property, you can always move the focus to any control with the mouse.

There is one control, the Option button, whose Tab order is handled specially. The members of an Option button group have a single Tab stop. Since ‘only one option button in the group can be checked  at a time, it doesn’t make sense to move the”focus from one to the other. A user who wants to change the status of an Option button through the keyboard can use the arrow buttons to check an Option button-an action that dears the previously selected button.

Posted on November 4, 2015 in Getting Started with Visual Basic

Share the Story

Back to Top