34
Visual Basic 6 Black Book:Advanced Form, Control, And Windows Registry Handling
Let’s see an example. In this case, when the user clicks the form, we’ll set the active
control’s Caption property to “Active Control”:
Private Sub Form_Click()
ActiveControl.Caption = "Active Control"
End Sub
The result of this code appears in Figure 28.1, where we indicate the active control
when the user clicks the form.
Figure 28.1 Indicating the active control in a form.
There’s a problem with this code, however—the form might contain all kinds of
controls, some of which (like text boxes) don’t even have a Caption property. If the
user clicks the form when one of those controls is the active control, an error will
result. To fix this potential problem, we can check the type of the active control before
working with it, and we’ll see how to do that in the next topic.
Determining Control Type At Runtime
In the previous topic, we set the caption of the currently active control (that is, the
control with the focus) to “Active Control” when the user clicked the form, but realized
there was a problem if the active control was one that didn’t have a Caption property.
To determine what type of control you’re working with at runtime, you can use
TypeOf keyword, which you can use to determine the type of any object. At first, it
seems odd that you might not know what kind of control you’re working with, but
cases like the current one—where we’re using the control now stored in the form’s
ActiveControl property—are very common in Visual Basic programming.
In the previous topic, we set the caption of the active control when the user clicked the
form like this:
Private Sub Form_Click()
ActiveControl.Caption = "Active Control"
End Sub
Now we can add code to check the active control’s type (possible types for Visual
Basic controls include CommandButton, CheckBox, ListBox, OptionButton,
HScrollBar, VScrollBar, ComboBox, Frame, PictureBox, Label, TextBox, and so
on) this way, making sure the active control is a command button before changing its
caption:
file:///E|/Program%20Files/KaZaA/My%20Shared%...sic%20-%20%20Black%20Book/ch28/0970-0974.html (3 of 5) [7/31/2001 9:05:57 AM]