Create object
The easiest way to create an object is to double-click the control in the Toolbox. However, to take full advantage of all objects available in Visual Basic and from other applications, you can use Visual Basic's programmability capabilities to create objects at run time.
1. Create object reference with object variable
2. Use class modules to create your own objects "from scratch"
3. Create your own collection using collection objects
Details on how to access objects are provided in other chapters. For example, the CreateObject and GetObject functions are discussed in Chapter 10, "Programming with Components."
Use object variables
In addition to storing values, variables can reference objects. Just like assigning a value to a variable, you can assign an object to a variable for the same reasons:
1. Variable names tend to be shorter and easier to remember than the values they contain (or, in this case, the objects they refer to).
2. When running code, variables should be changed in order to reference other objects.
3. Referring to the variable containing the object is more efficient than repeatedly referencing the object itself.
Using object variables is the same as using regular variables, except that there is an additional step of assigning the object to the variable:
4. First declare the variables:
DimvariableAsclass
5. Then assign the object to the variable:
Setvariable=object
Declare object variables
The method of declaring object variables is the same as declaring other variables, using Dim, ReDim, Static, PRivate and Public. The only difference is the optional New keyword and Class parameters, which will be introduced later in this chapter. The syntax is:
{Dim|ReDim|Static|Private|Public}variableAs[New]class
For example, you can declare an object variable that references a form in your application called frmMain:
DimFormVarAsNewfrmMain 'Declare a type as frmMain
' object variable.
You can also declare an object variable that references any form in your application:
DimanyFormAsForm 'General form variables.
Similarly, you can declare an object variable that can reference any text box in your application:
DimanyTextAsTextBox 'can reference any text box
' (but only a text box).
You can also declare an object variable, which can reference any type of control:
DimanyControlAsControl 'General control variables.
Note that you can declare a form variable that references a specific form in your application, but you cannot declare a control variable that references a specific control. You can declare a control variable that references a specific type of control (such as a TextBox or a ListBox), but not a specific control of that type (such as a txtEntry or List1). However, specific controls can be assigned to variables of that type. For example, a form with a list box lstSample could be coded like this:
DimobjDemoAsListBox
SetobjDemo=lstSample
Assignment object variable
Use the Set statement to assign the object to the object variable:
Setvariable=object
Whenever you want an object variable to refer to an object, you can use the Set statement.
Sometimes you can use object variables, especially control variables, to directly shorten the code you type. For example, the original code looks like this:
IffrmAccountDisplay!txtAccountBalance.Text<0Then
frmAccountDisplay!txtAccountBalance.BackColor=0
frmAccountDisplay!txtAccountBalance.ForeColor=255
EndIf
If you use control variables, your program can be significantly shortened:
DimBalAsTextBox
SetBal=frmAccountDisplay!txtAccountBalance
IfBal.Text<0Then
Bal.BackColor=0
Bal.ForeColor=255
EndIf
Specific object types vs. general object types
A specific object variable must refer to a specific type of object or class. A specific form variable can reference only one form in the application (although it can be referenced in one of many instances of that form). Similarly, a specific control variable can only refer to a specific type of control in the application, such as a TextBox or a ListBox. Please see an example, open a new project and place a text box in the form. Add the following code to the form:
PrivateSubForm_Click()
DimanyTextAsTextBox
SetanyText=Text1
anyText.Text=Hello
EndSub
Run the application and click on the form. The text box's Text property will change to Hello.
General object variables can reference one of several specific object types. For example, a general form variable can reference any form in the application; a general control variable can reference any control on any form in the application. Please see an example, open a new project and place several Frame, Label and CommandButton controls in any order on the form. Add the following code to the form:
PrivateSubForm_Click()
DimanyControlAsControl
SetanyControl=Form1.Controls(3)
anyControl.Caption=Hello
EndSub
Run the program and click on the form. The title of the third control you just placed on the form will change to Hello.
There are four general objects in Visual Basic:
General object variables are useful when it is not known at run time whether the variable refers to an object of a specific type. For example, if you want to write code that works on any form in your application, you must use general form variables.
Note that since there can only be one MDI form in the application, it is not necessary to use the general MDIForm type. Whenever you need to declare a form variable that references an MDI form, you can use a specific MDIForm type (either MDIForm1, or whatever name you specify on the MDI form's Name property) instead of the general MDIForm type. In fact, you should always use a specific MDIForm type because Visual Basic can determine the properties and methods that reference a specific form type before running the application.
The general MDIForm type is provided only for completeness; it will be useful in future versions of Visual Basic to have multiple MDI forms in a single application.
form as object
Forms are most commonly used to construct application interfaces, but they are also often objects called by other modules in the application. Forms are closely related to class modules. The main difference between the two is that forms are visual objects, while class modules have no visual interface.
Add custom methods and properties
Custom methods and properties can be added to the form and accessed from other modules in the application. To create new methods for a form, add a procedure declared with Public.
'Method to customize Form1.
PublicSubLateJobsCount()
.
. '<statements>
.
EndSub
The LateJobsCount procedure can be called from other modules using the following statement:
Form1.LateJobsCount
Creating new properties for a form is as simple as declaring a public variable in the form module:
PublicIDNumberAsInteger
The following two statements can be used to set and return the IDNumber value of Form1 from other modules:
Form1.IDNumber=3
Text1.Text=Form1.IDNumber
You can also use the Property procedure to add custom properties to a form.
Details Chapter 9, "Programming with Objects," provides detailed material on the Property procedure.
Note that you can call the form's variables or custom methods without loading the form, and you can also set the form's custom properties. As a result, you can run code about the form without loading it into memory. Likewise, referencing a control without referencing its properties or methods will not load the form.
Use the New keyword
Use the New keyword to create a new object, which is treated as the object defined by its class. New can be used to create instances of collections, forms, and classes defined in class modules.
Use the New keyword on a form
Forms created at design time are classes. New instances of this class can be created using the New keyword. To see this process in action, draw a command button and several other controls on the form. In the Properties window, set the form's Name property to Sample. Add the following code in the command button's Click event procedure:
DimxAsNewSample
x.Show
Run the application and click the command button several times. Move the frontmost form aside. Because the form is a class with a visual interface, additional copies are visible. Each form has the same controls in the same locations where the form was designed.
Note that to make form variables and instances of loaded forms always exist, use Static or Public variables instead of local variables.
You can also use the New keyword with the Set statement. Please try the code in the Click event procedure of the command button:
DimfAsForm1
Setf=NewForm1
f.Caption=hello
f.Show
Using the New keyword with the Set statement will speed up the execution, so this method is recommended.
Use the New keyword with other objects
You can use the New keyword to create collections and objects from classes defined in a class module. Use the following example to illustrate this working process.
This example illustrates how the New keyword creates an instance of a class. Open a new project and draw a CommandButton control on Form1. Select the Add Class Module command from the Project menu to add a class module to the project. Set the Name property of the class module to ShowMe.
The following code in Form1 creates a new instance of class ShowMe and calls a procedure contained in the class module.
PublicclsNewAsShowMe
PrivateSubCommand1_Click()
SetclsNew=NewShowMe
clsNew.ShowFrm
EndSub
The ShowFrm procedure in the class module creates a new instance of class Form1, displays the form, and then minimizes it.
SubShowFrm()
DimfrmNewAsForm1
SetfrmNew=NewForm1
frmNew.Show
frmNew.WindowState=1
EndSub
To apply this example, run the application and click the command button several times. You will see a minimized form icon appear on the desktop as each new instance of the ShowMe class is created.
For more information about using New to create objects, see Chapter 10, "Programming with Components."
New keyword restrictions
The following table explains what you cannot do with the New keyword.
Release the reference to the object
Every object uses memory and system resources. It is good programming practice to release these resources promptly when the object is no longer used.
Use Unload to unload a form or control from memory.
Use Nothing to release the resources occupied by object variables. Use the Set statement to assign Nothing to the object variable.
For more information, please refer to the "Unload Event" and "Nothing" sections in the "Visual Basic 6.0 Language Reference Manual".
Pass object to procedure
Objects can be passed to procedures in Visual Basic. In the following code example, it is assumed that the form has a CommandButton control:
PrivateSubCommand1_Click()
'Call the Demo subroutine and pass it the form.
DemoForm1
EndSub
PrivateSubDemo(xAsForm1)
'Center the form on the screen.
x.Left=(Screen.Width-x.Width)/2
EndSub
You can pass an object to a parameter by reference and then set the parameter to a new object within the procedure. To see this in action, open the project and insert a second form. Place a picture box in each form. The attribute setting values that need to be changed are as shown in the following table:
The Form1_Click event procedure calls the GetPicture procedure in Form2 and passes it an empty picture box.
PrivateSubForm_Click()
Form2.GetPicturePicture1
EndSub
The GetPicture process in Form2 assigns the Picture property of the picture box on Form2 to the empty picture box on Form1.
PrivateobjXapictureBox
PublicSubGetPicture(xAsPictureBox)
'Assign the passed in picture frame to the object variable.
SetobjX=x
'Assign the Picture attribute value to the picture box of Form1.
objX.Picture=picture2.Picture
EndSub
To apply this example, run the program and click on Form1. You will see the icon in Form2 appear in the picture box of Form1.
Details The above topics are intended to provide an overview of the objects. For more details, see Chapter 9, "Programming with Objects" and Chapter 10, "Programming with Components."
->