home | links | contact


 

Visual Basic 6.0 Study Guide

Program Structure

A typical application consists of one or more modules: a form module for each form in the application, optional standard modules for shared code, and optional class modules.

Each module contains one or more procedures that contain the code: event procedures, Sub or Function procedures, and Property procedures.

 

Startup Form can be set in Project Properties.

Sub Main() can only be in a standard module. To display a splash screen, use a Sub Main procedure as startup object and use the Show method to display the form:

Private Sub Main()

   frmSplash.Show  ' Show the splash screen.

      …            ' Add startup procedures here.

   frmMain.Show    ' Show the main form and unload the splash screen.

   Unload frmSplash

End Sub

 

Three ways to end an application:

PRIVATESingle Form

Multiple Forms

Private Sub cmdQuit_Click ()

   Unload Me

End Sub

Private Sub Form_Unload (Cancel As Integer)

   Dim i as integer

   ' Loop through the forms collection and unload

   ' each form.

   For i = Forms.Count – 1 to 0 Step - 1

      Unload Forms(i)

   Next

End Sub

End statement

Ends an application immediately: no code after the End statement is executed, and no further events occur. Object references will be freed, but if you have defined your own classes, Visual Basic will not execute the Terminate events of objects created from your classes.

 

Life Cycle of Visual Basic Forms

1.      Created, but not loaded. (Initialize) This is the only state all forms pass through.

2.      Loaded, but not shown. (Load) Create Controls. Assign hWin, hDC.

3.      Shown.

(Resize) - Occurs when an object is first displayed or when the window state of an object changes. (For example, a form is maximized, minimized, or restored.)

(Activate) - Occurs when an object becomes the active window.

(Paint) - Occurs when part or all of an object is exposed after being moved or enlarged, or after a window that was covering the object has been moved.

4.      Memory and resources completely reclaimed.

(QueryUnload) – Prompt user for saving.

(Unload) - Remove from Forms Collection. Module-level variables may still exist.

The only way to release all memory and resources is to unload the form and then set all references to Nothing. Set Form1 = Nothing

(Terminate)

Executing the End statement unloads all forms and sets all object variables in your program to Nothing. However, this is a very abrupt way to terminate program. None of the forms will get their QueryUnload, Unload, or Terminate events, and objects created will not get their Terminate events.

5.      Unloaded and unreferenced while a control is still referenced.

 

 

Object Concept

Objects in Visual Basic are created from classes; thus an object is said to be an instance of a class. The class defines an object’s interfaces, whether the object is public, and under what circumstances it can be created. Descriptions of classes are stored in type libraries, and can be viewed with object browsers.

To use an object, you must keep a reference to it in an object variable. The type of binding determines the speed with which an object’s methods are accessed using the object variable. An object variable can be late bound (slowest), or early bound.

Early-bound variables can be DispID bound or vtable bound (fastest).

A set of properties and methods is called an interface. The default interface of a Visual Basic object is a dual interface which supports all three forms of binding. If an object variable is strongly typed (that is, Dim … As classname), it will use the fastest form of binding.

Using Code Editor

In a form module, the list includes a general section, a section for the form itself, and a section for each control contained on the form.

For a class module, the list includes a general section and a class section; for a standard module only a general section is shown.

Class modules list only the event procedures for the class itself — Initialize and Terminate. Standard modules don't list any event procedures, because a standard module doesn't support events.

Breaking and combining statements

Text1.Text = "Hello" : Red = 255 : Text1.BackColor = _

Red

 

 

Declaring Variables

Dim variablename [As type]

·        Declaring a variable in the Declarations section of a form, standard, or class module, rather than within a procedure, makes the variable available to all the procedures in the module.

·        Declaring a variable using the Public keyword makes it available throughout your application.

·        Declaring a local variable using the Static keyword preserves its value even when a procedure ends.

·Implicit Declaration - You don't have to declare a variable before using it.

Explicit Declaration - Using "Option Explicit"

·        The Option Explicit statement operates on a per-module basis; it must be placed in the Declarations section of every form, standard, and class module for which you want Visual Basic to enforce explicit variable declarations. If you select Require Variable Declaration, Visual Basic inserts Option Explicit in all subsequent form, standard, and class modules, but does not add it to existing code. You must manually add Option Explicit to any existing modules within a project 

·Scoping Variables

Depending on how it is declared, a variable is scoped as either a procedure-level (local) or module-level variable.

PRIVATEScope

Private

Public

Procedure-level

( Dim, Static )

Variables are private to the procedure in which they appear.

Not applicable. You cannot declare public variables within a procedure.

Module-level

( In Declaration Section )

Variables are private to the module in which they appear.

Variables are available to all modules.

Values in local variables declared with Static exist the entire time your application is running while variables declared with Dim exist only as long as the procedure is executing. At the module level, there is no difference between Private and Dim. You can't declare public variables within a procedure.

Static Function or Sub will make all the local variables in the procedure static regardless their declaration inside.

Constant has the same scope rule as variable does.

 

Friend members is suitable in the ActiveX components. Friend functions are not part of an object's interface. They can't be accessed by programs that use the component's objects. They're only visible to all the other objects within the component to allow safe internal communication within the component.

Because Friend members aren't part of an object's public interface, they can't be accessed late bound — that is, through variables declared As Object. To use Friend members, you must declare variables with early binding — that is, As classname.

The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. A Friend procedure doesn't appear in the type library of its parent class, nor can a Friend procedure be late bound.

Friend makes the procedure visible throughout the project, but not to a controller of an instance of the object.

 

Name Conflicting and Resolving

The forms and controls can have the same name as a restricted keyword. To resolve conflict, using:

·        MyForm.Loop.Visible = True ' Qualified with the form name.

·[Loop].Visible = True ' Square brackets also work.

Within the form module, local variables with the same names as controls on the form shadow the controls.

To resolve conflict, using: a reference or keyword Me

Private Sub Form_Click ()

Dim Text1    ' Assume there is also a control on the form called Text1.

   Text1 = "Variable"    ' Variable shadows control.

   Text1.Top = 0         ' This causes an error!

   Me.Text1.Top = 0      ' Must qualify with Me to get

End Sub

A variable in the module cannot have the same name as any procedures or types defined in the module. It can, however, have the same name as public procedures, types, or variables defined in other modules. In this case, when the variable is accessed from another module, it must be qualified with the module name.

Constant Name is referenced in case of collision depends on which object library has the higher priority.

To resolve conflict, using: [libname.][modulename.]constname

 

Data types

Dim EmpName As String * 50

Fixed-length strings in standard modules can be declared as Public or Private. In forms and class modules, fixed-length strings must be declared Private. You can assign a string to a numeric variable if the string represents a numeric value.

The default value of Boolean variable is False.

Object variable is actual a 32-bit pointer referring to an object within an application or within some other application. Using the Set statement to refer to any actual object recognized by the application.

·        Dim objDb As Object ‘or Database

·Set objDb = OpenDatabase("c:\Vb5\Biblio.mdb")

By default, if you don't supply a data type, the variable is given the Variant data type. A Variant variable is capable of storing all system-defined types of data. You don't have to convert between these types of data if you assign them to a Variant variable; Visual Basic automatically performs any necessary conversion. For example:

Dim SomeValue      ' Variant by default.

SomeValue = "17"   ' "17" (a two-character string)

SomeValue = SomeValue - 15    ' numeric value 2

SomeValue = "U" & SomeValue   ' "U2" (a two- character string)

·        If you perform arithmetic operations on a Variant, the Variant must contain something that is a number.

·        If you are concatenating strings, use the & operator instead of the + operator.

·        Variants can contain three special values: Empty, Null, and Error.

·        Empty is used to see if a value has ever been assigned to a created variable.

·        Null is commonly used in database applications to indicate unknown or missing data. Null will propagate through expressions involving Variant variables. Variables are not set to Null unless you explicitly assign Null to them.

·        Error is a special value used to indicate that an error condition has occurred in a procedure. Error values are created by converting real numbers to error values using the CVErr function.

·Note: A variant always takes up 16 bytes, no matter what you store in it. Objects, strings, and arrays are not physically stored in the Variant; in these cases, four bytes of the Variant are used to hold either an object reference, or a pointer to the string or array. The actual data are stored elsewhere.

 

 

ParamArray

·        It can only be used in as the final argument in an argument list.

·        It represents an optional array of variant Data type

·        It cannot be used with ByVal, ByRef or Optional keywords

·        It is used in these contexts:

·        Declare Statement

·        Function Statement

·        Property Get Statement

·        Property Let Statement

·        Sub Statement

·You create a user-defined type with the Type statement, which must be placed in the Declarations section of a module.

User-defined types are always passed by reference.

·        Public Type udtAccount

·   Number As Long

   Type As Byte

   CustomerName As String

   Balance As Double

End Type

 

Enumeration data type

As you may know, Visual Basic doesn't allow public constants in a class
module. 

However, if that works for you, then consider including a Public Enum
statement in your class. The Enum statement provides for enumeration
of variables. If you provide constant values for the elements, then Visual Basic uses
those values. If you don't provide values, then Visual Basic starts
the list at 0 and increments each element's value by one.

 

 

Public Enum WorkDays

   Saturday

   Sunday = 0

   Monday

   Tuesday

   Wednesday

   Thursday

   Friday

   Invalid = -1

End Enum

 

Arrays

Dim Sums(20) As Double ' 21 elements. The default lower bound is 0.

Dim Counters(1 To 15) As Integer

Dim MultiD(3, 1 To 10, 1 To 15) 'multi-dimension

Dim DynArray()        'dynamic array

ReDim DynArray(4 to 12) 'is an executable statement, can appear only in a procedure

ReDim Preserve DynArray(UBound(DynArray) + 1)    'reserve the old values

 

·        ReDim Preserve Matrix(UBound(Matrix, 1) + 1, 10) 'Error: Only the upper bound of the last 'dimension in a multidimensional array can be changed

 

Collections

A collection is an ordered set of items that can be referred to as a unit. What makes the Collection object so useful is that the items it contains can be essentially anything--variables, literal numbers or text, objects, and so on. What's more, they do not have to be the same data type.

 

Dim col As New Collection

 

You use the Add method to add items to the collection:

 

col.Add item, key, before, after

 


To retrieve an item from a collection use the Item method:

col.Item(index)

 

Dim col As New Collection

Then, when each window is created add it to the collection:

 

Dim f As New Form2
col.Add f
f.Show

When it's time to close all the windows, loop through the collection like this:

 

Dim i As Integer
Dim f As Form
For i = 1 To col.Count
Set f = col(i)
f.Visible = False
Set f = Nothing
Next

·You may want to use a collection instead of array if you're working with a small, dynamic set of items.

·A Collection object stores each item in a Variant. A Collection object has three methods (add, item, remove) and one property (count). Collection are not polymorphic.

·Forms collection contains all of the currently loaded Visual Basic forms in the program. Collection class contains anything that can be stored in a Variant. Thus the Collection object can contain an object or an integer, but not a user-defined type.

 

 

·control array

·A group of controls that share a common name, type, and event procedures. Each control in an array has a unique index number that can be used to determine which control recognizes an event.

 

There are three ways to create a control array at design time:

 

Assign the same name to more than one control.

Copy an existing control and then paste it onto the form.

Set the control's Index property to a value that is not Null.

Note: You must create menu control arrays in the Menu Editor.

 

At run time, use:

Load   Object(index%)

Unload Object(index%)

·        The control must be created at design-time to be ready loaded at run-time. You can use the Unload statement to remove any control created with Load. However, you cannot use Unload to remove controls created at design time.

 

Procedure

Declaration Statement

[Public | Private] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])]

[Public | Private] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type]

 

??????     Sub procedures are by default Public in all modules, which means they can be called from anywhere in the application. ?????

 

 There are two types of Sub procedures, general procedures and event procedures.

Sub ButtonManager(Button As Control) ‘general procedure, usually in bas. module

Private Sub cmdUp_Click() ‘event procedure

There are two ways to call a Sub procedure:

' Both of these statements call a Sub named MyProc.

Call MyProc (FirstArgument, SecondArgument)

MyProc FirstArgument, SecondArgument

 

Function has return value.

There are three ways to call a Function procedure:

X = functionForX

Call function(x)     ‘will throw away return value

Function x           ‘will throw away return value

 

Argument

Sub ListText(ByVal x As String, Optional y As _Integer = 12345)

Using the ParamArray keyword allows you to specify that a procedure will accept an arbitrary number of arguments.

ParamArray is used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments.

The ParamArray keyword can't be used with ByVal, ByRef, or Optional.

Named argument for many built-in functions, statements, and methods:

 

Function ListText(strName As String, Optional strAddress As String)

   List1.AddItem strName

   List2.AddItem strAddress

End Sub

 

Private Sub Command1_Click()

   ListText strAddress:="12345", strName:="Your Name" ‘in reverse order

End Sub

 

Control Structure

For Each element In group
statements

Next element

This is helpful if you don't know how many elements are in a collection.

·        For collections, element can only be a Variant variable, a generic Object variable, or an object listed in the Object Browser.

·        For arrays, element can only be a Variant variable.

·        You cannot use For Each...Next with an array of user-defined types because a Variant cannot contain a user-defined type.

·        Exit For … Exit Do … Exit Sub … Exit Function ‘exit control structure

 

 

·Object

Properties that you can set and get at run time are called read-write properties. Properties you can only read at run time are called read-only properties.

There are some common cases in Visual Basic where one object contains other objects. Forms, Controls, Printers.

 

Three ways to refer a collection member:

Controls("List1")

Controls!List1

Controls(3)

You can use the Container property to change an object's container within a form.

The following controls can contain other controls:

·        Frame control

·        Picture box control

·        Toolbar control (Professional and Enterprise editions only)

 

 

Menu

Each menu you create can include up to five levels of submenus.

Ctrl+E: Menu Editor

A menu control array is a set of menu items on the same menu that share the same name and event procedures. Each menu control array element is identified by a unique index. Use a menu control array to:

·        Create a new menu item at run time when it must be a member of a control array. For example, a menu control array may be used to store a list of recently opened files.

·        Simplify code, because common blocks of code can be used for all menu items.

·Elements of a menu control array must be contiguous in the menu control list box and must be at the same level of indentation. When you're creating menu control arrays, be sure to include any separator bars that appear on the menu.

 

 

What is the restrictions of dynamically created menu items?

 

Cannot have shortcut keys

Cannot be used for a WindowList

Must be menu control array elements

 

Pop-up menu

 

Private Sub Form_MouseUp (Button As Integer, Shift As _

   Integer, X As Single, Y As Single)

   If Button = 2 Then   ' Check if right mouse button was clicked.

      PopupMenu mnuFile ' Display the File menu as a pop-up menu.

   End If

End Sub

·        Any code following a call to the PopupMenu method is not run until the user selects an item in the menu or cancels the menu. Only one pop-up menu can be displayed at a time. While a pop-up menu is displayed, calls to the PopupMenu method are ignored. Calls to the PopupMenu method are also ignored whenever a menu control is active.

Menu and toolbar negotiation will occur only for insertable objects that support in-place activation.

1.                     The NegotiateMenus property does not apply to MDI Forms.

2.                     The NegotiateToolbars property applies only to MDI forms.

 

 

There are three ways to set conditional compilation constants:

·        Project Properties dialog box - Public to all modules in the project

·        Command line - Public to all modules in the project

·        vb6.exe /make MyProj.vbp /d conFrenchVersion=–1:conANSI=0

·        #Const statement in code - Private to the module in which they are declared.

·        - Only conditional compiler constants and literals can be used in expression.

·Conditional compilation can use literal statements except for IS operator.

 

Class Module

 

·Property procedures

·Property Get - Returns the value of a property.

·Property Let - Sets the value of a property.

Let x = 3 

Property Set - Sets the value of an object property.

 

– Set objThing = New Thing

·        Property procedures are public by default.

·        The Property Get declaration must use arguments with the same name and data type and less one number as the arguments in the Property Let procedure.

·        The data type of the final argument in a Property Set declaration must be either an object type or a Variant.

·        To create a read-only property, simply omit the Property Let or (for object properties) the Property Set.

 

 

Event

An object that raises events is called an event source. To handle the events raised by an event source, you can declare a variable of the object's class using the WithEvents keyword. WithEvents variables must be module-level variables.

Option Explicit

Private WithEvents mWidget As Widget

 

Limitations on WithEvents Variables

·        A WithEvents variable cannot be a generic object variable. That is, you cannot declare it As Object.

·        You cannot declare a WithEvents variable As New.

·        You cannot declare WithEvents variables in a standard module.

·        You cannot create arrays of WithEvents variables.

·Inside Class module, use Public EventRaiseEvent… pair. Events are always Public.

 

 

DragOver event determines what happens after dragging is initiated and before a control drops onto a target. This event occurs only if OLEDropMode is set to 1 (Manual).

Private Sub Form_DragOver(source As Control, x As Single, y As Single, _

state As Integer)

 

Source - The control being dragged.

State  - The transition state of the control being dragged in relation to a target form or control. 0: enter, 1: leave, 2: over.

 

Private Sub object_OLEDragOver(data As DataObject, effect As Long, button _

As Integer, shift As Integer, x As Single, y As Single, state As Integer)

 

Moving DataObject (not Control) from one control or application to another.

KeyDown and KeyUp events occur when the user presses (KeyDown) or releases (KeyUp) a key while an object has the focus. (To interpret ANSI characters, use the KeyPress event.)

 

Polymorphism

 

VB supports Interface inheritance by two steps:

1.                     Define interfaces – a class module by adding methods without code.

2.                     Define Child class using keyword Implements, then implement all the properties and methods of parent interface.

 

Option Explicit

Implements Animal

Private Sub Animal_Move(ByVal Distance As Double)

              Debug.Print "Flea moved"

End Sub

 

VB doesn’t support aggregation.

 

 

 

Component Programming

To declare an object variable for an object not defined in a type library

Dim objAny As Object

 

The main difference between declaring a variable of a specific class and declaring a variable of the generic Object class is in how ActiveX binds the variable to the object. When you declare a variable of the generic Object class, ActiveX must use late binding. When you declare an object variable of a specific class, ActiveX uses early binding, which can speed object references.

Assigning an Object reference

If the ActiveX component supplies a type library, using NEW

If not, using

Set objectvariable = CreateObject("progID", ["servername"])

Or Set objectvariable = GetObject([pathname] [, progID])

For example:

Dim xlApp As Object

Set xlApp = CreateObject("Excel.Application") ‘late binding

 

Dim wdApp As Word.Application

Set wdApp = GetObject("", "Word.Application")

Set X = GetObject(, "MySrvr.Application")

X references an existing Application object.

Dependent objects are lower in an object hierarchy, and they can be accessed only by using a method of an externally creatable object. Defined by Class Instancing property - PublicNotCreatable.

Data associated with an embedded object is not persistent; that is, when a form containing an OLE container control is closed, any changes to the data associated with that control are lost. To save updated data from an object to a file, you use the OLE container control's SaveToFile method.

Private Sub cmdSaveObject_Click ()

   Dim FileNum as Integer   ' Get file number.

   FileNum = FreeFile       ' Open file to be saved.

   Open "TEST.OLE" For Binary As #FileNum   ' Save the file.

   oleObj1.SaveToFile FileNum               ' Close the file.

   Close #FileNum

End Sub

If the object is linked, then only the link information and an image of the data is saved to the specified file. The object's data is maintained by the application that created the object. If a user wants to save changes to a linked file, the user must choose the Save command from the ActiveX component's File menu because the SaveToFile method applies only to embedded objects.

 

Asynchronous notifications and implementation

A client makes a method call and tells the component it wants to be notified when certain things happen. Then the client can be free to do other things while it’s waiting for component notification. Two implementations: An event is like an anonymous broadcast, while a call-back is like a handshake

 

 

3.                     Using eventsRaiseEvent - WithEvents

Using Call-back

Test ActiveX Component

To test a component, you need to create a client application. If you’re creating components as part of an application, you can use the application itself as the test program. The test project must be an Exe project. To test call-backs, use an ActiveX Exe project.

To test In-process server:

4.                     Create a Project Group containing the component and test project.

5.                     Set test project as active project and make a reference to the component. ( not necessary for ActiveX control)

6.                     Add code to test the properties and methods of each public class provided by your component.

 

 

To test Out-of-process server:

·        Make <project name> Component executable.

·        Ctrl+F5 to run component project. You cannot add a reference to the component project unless it’s in run mode.

·        Open a second instance of the Visual Basic development environment.

·        Start a new test project and make a reference to the component.

·        Add code to test the properties and methods of each public class provided by your component.

·The difference between debugging controls and debugging other objects is that some of the code in your control must execute while the testing form is in design mode. To put a control into a state such that its code can execute at design time, you must close the control's visual designer to enable the control's icon in the Toolbox.

 

 

Software Distribution

Three ways to start the Package and Deployment Wizard:

1.                                             In your application project, start from Add-In

2.                                             Run it as a stand-alone component from outside IDE.

3.                                             Start it in silent mode by launching it from a command prompt. Unattended with script.

·        PDCmdLn.exe C:\Project1\Project1.vbp /p "Internet Package" /d Deployment1

/l "C:\Project1\SilentMode.log"

Signing and licensing must be done outside of the packaging process.

 

A dependency (.dep) file contains information about the run-time requirements of an application or component. In Visual Basic, dependency information is stored in files generated by the Package and Deployment Wizard or created manually by you.

·        Component Dependency File: A .dep file lists all the files required by a particular component. When you purchase or use a component from a vendor, you receive a .dep file from them.

·        The VB6dep.ini file provides the Package and Deployment Wizard with an all-purpose list of dependencies and references used by Visual Basic. This list is created when you install Visual Basic and resides in the \Wizards\PDWizard subdirectory of the main Visual Basic directory.

For a standard package, the information from the .dep files is written to a Setup.lst file that is stored outside the packaged .cab file.

For an Internet package, the .dep file information is written to an .inf file that is stored within the packaged .cab file.

The Setup Toolkit is a project installed with Visual Basic that is used by the Package and Deployment Wizard when it creates a setup program, setup1.exe. By default, the Setup Toolkit uses the \Program Files directory as the root location. When installing a file on the user's machine, you should not copy an older version of the file over a new version.

The Setup.lst file describes all the files that must be installed on the user's machine for your application and contains crucial information for the setup process.

 

Internet Distribution

The Setup Wizard will create a .cab file, known as the primary .cab file, which contains:

·        The project components, such as the ActiveX control, ActiveX DLL, or ActiveX EXE

·        The .inf file, which contains links to other .cab files that contain Visual Basic support files and controls, as well as other information, such as whether the control is safe for scripting and safe for initialization and registry information as defined by the user. This file replaces the Setup.lst file that the Setup Wizard creates in the standard setup.

·        Reserved space for digital signatures.

·        All files that are not in other (secondary) .cab files. Secondary .Cab Files: For ActiveX control projects, ActiveX EXEs, and ActiveX DLLs, all run-time components such as Msvbvm50.dll, individual controls, Data Access Objects (DAO), and Remote Data Objects (RDO) are packaged into separate .cab files, digitally signed by Microsoft, and placed on the Microsoft Web site. You can choose to link your files to the .cab files on the Microsoft Web site, or you can download local copies of them.

When you compile a ActiveX control with licensing support. The .VBL file will contain licensing info(use the "Requiere License"Key option, located in the General tab of the Project Properties dialog box.)

Only an ActiveX control can be used with the Create Download Setup option in the Setup Wizard.

ActiveX documents use the NavigateTo method to get to URL Adresses on WWW. The ActiveX document must be in a hyperling-aware containter and in a container that maintains a history of documents to use the "goBack" and "goForward" methods to move between previously visited documents.

Advantages of Using ActiveX Documents:

·        Support for the Hyperlink object

·        Support for the AsyncRead method

·The benefit of using secondary .cab files from a Web site are:

You do not need to distribute all of the .cab files required by your application. The only file you need to distribute is the primary .cab file. The .inf file within the primary .cab file points to the Microsoft Web site and downloads the necessary .cab files based on the needs of the end user. They provide an efficient means of delivering updates to your product. If you cannot or do not want your application setup to require a connection to the Internet, you may place the secondary .cab files on a ser<

·        Create a file with a name supplied by a script.

·        Read a file from the user's hard drive with a name supplied by a script.

·        Insert information into the Windows Registry (or into an .ini file), using a key (or filename) supplied by a script.

·        Retrieve information from the Windows Registry (or from an .ini file), using a key (or filename) supplied by a script.

·        Execute a Windows API function using information supplied by a script.

·        Create or manipulate external objects using programmatic IDs (for example, "Excel.Application") that the script supplies.

A safe for initialization control does not write or modify any registry entries, .ini files, or data files as a result of initialization parameters.

The downloaded license key is not added to the registry. Instead, browser asks the control to create a run-time instance of itself, and passes it the downloaded license key.

Only the DBGrid control requires a license key on a Web server.

There is a fine line between a safe and unsafe action. For example, a control that always writes information to its own registry entry may be safe. A control that allows you to name the registry entry is unsafe. A control that creates a temporary file with a name it creates without using any initialization or scripting value may be safe. A control that allows the name of the temporary file to be assigned at initialization or by scripting is unsafe.

A control marked safe for initialization guarantees to do nothing bad no matter what data it is initialized with The critical issue is what may happen as a result on initialization with particular values. A control that automatically sends information at initialization to an HTTP server may be safe, as long as the server address cannot be changed. You may create files and any other activities needed for the control as long as the file properties (name, file size) or activity’s nature does not change becau

MSDN, "Deploying ActiveX Controls on the Web with the Internet Component Download"

?

Registry

GetSetting(application_name, section, key[, default])

Returns a key setting value from an application's entry in the Windows registry.

SaveSetting and DeleteSetting statements

·        SaveSetting appname := "MyApp", section := "Startup", key := "Top", setting := 75

·SaveSetting "MyApp","Startup", "Left", 50

' Remove section and all its settings from registry.

DeleteSetting "MyApp", "Startup"

 

All applications created in VB use a predefined Registry location: HKEY_CURRENT_USER\SOFTWARE\VB and VBA Program Settings\Appname\Section\Key.

 

How to find out the components that are registered in your computer?             Regsrv32.exe

Which types of files can you register by using Regsrv32.exe? Dll, Exe, OCX

 

 

Help features

The HelpFile property of the App object is used to specify the file name of the Help file for your application. It requires a valid WinHelp (.hlp) or HTML Help (.chm) file. If the file doesn't exist, an error will occur. This property can be set in:

1.                                             Project property windows

2.                                             By programming:

·        Private Sub Form_Load()

·   App.HelpFile = App.Path & "\foo.chm"

End Sub

The HelpContextID property is used to link a user interface element (such as a control, form, or menu) to a related topic in a Help file. The HelpContextID property must be a Long that matches the Context ID of a topic in a WinHelp (.hlp) or HTML Help (.chm) file. If the user presses F1 on a control with a HelpContextID of 0 (the default), Visual Basic will search for a valid HelpContextID for the control's container.

The ShowHelp method of the CommonDialog control runs the Windows Help Engine (WINHLP32.EXE) and displays a help file that is set by the HelpFile property. By setting the HelpCommand property, you can tell the help engine what type of online help you want, such as context sensitive or help on a particular keyword, etc.

 

Data and Bound Controls

 

 

Textbox Validate Event

Set the CausesValidation property of surrounding controls to True. This insures that the Validate event of the TextBox control will fire when the TextBox control attempts to lose focus to one of these controls. The routines could be coded as follows:

 

Private Sub Text1_Validate(Cancel As Boolean) 'Validate the input data. Highlight the offending text.

    If Not IsDataValid(Text1.Text) Then

'Set the focus back and highlight the text

. Text1.SelStart = 0

Text1.SelLength = Len(Text1.Text)

Cancel = True   ‘set to true to prevent lose focus

    End If

End Sub

Where IsDataValid – user defined function

 

ListBox

To add or delete items in a ListBox control, use the AddItem or RemoveItem method. Set the List, ListCount, and ListIndex properties to enable a user to access items in the ListBox. The Style property sets ListBox as Standard or CheckBox. The Columns property determines how many columns are displayed. Filling the first column, then the second column, and so on. This property can't be set to 0 or c<

Data-aware control: Provides access to a specific field or fields in a database through a Data control. A data-aware control is typically bound to a Data control through its DataSource and DataField properties. When a Data control moves from one record to the next, all bound controls connected to the Data control change to display data from fields in the current record. When users change data in a bound control and then move to a different r<>

You should add error handlers to any procedure where you anticipate the possibility of an error.

Visual Basic searches backward in the calls list to execute the first enabled error handler it finds. If not, it presents a default unexpected error message and halts execution.

The Err object is used to obtain information about errors that have occurred during program execution. When a run-time error occurs, the generator of the error sets the properties of the Err object. These properties identify the error and allow you to handle it in your code. The Err object has a Raise method that allows you to generate your own errors and set the properties of the Err object yourself when you know that something has gone wrong in your code.

The Number property of the Err object contains a numeric code representing the most recent run-time error.

For example:

 

Dim Msg

' If an error occurs, construct an error message

On Error Resume Next   ' Defer error handling.

Err.Clear

Err.Raise 6   ' Generate an "Overflow" error.

' Check for error, then show message.

If Err.Number <> 0 Then

   Msg = "Error # " & Str(Err.Number) & " was generated by " _

         & Err.Source & Chr(13) & Err.Description

   MsgBox Msg, , "Error", Err.Helpfile, Err.HelpContext

End If

Disable an error trap: On Error GoTo 0

 

DLL

If you declare a DLL procedure or function in a Form, it is private to that Form. To make it public, you must declare it in a Module.

Some DLL procedures can accept more than one type of data for the same argument. To pass more than one type of data, declare the argument with the As Any keyword to remove type restrictions. Such as:

·        Declare Function FindWindow Lib "user32" Alias "FindWindowA" _

· (ByVal lpClassName As Any, ByVal lpWindowName As Any) As Long

Occasionally, a DLL procedure has a name that isn’t a valid identifier in Microsoft Access. It may have an invalid character (such as a hyphen), or be the same as a Visual Basic keyword (such as GetObject). When either is the case, use the Alias keyword.

In addition to a name, all DLL procedures can be identified by an ordinal number that specifies the position of the procedure in the DLL. Visual Basic is using the ordinal number to find the procedure in the DLL. To declare a DLL procedure by ordinal number, use the Alias keyword and #. Such as:

·        Declare Function GetAppSettings Lib "Utilities" Alias "#47" () As Long

·When passing strings, you must use the ByVal keyword to convert a Visual Basic string into a null-terminated string. However, strings are always passed to DLL procedures by reference even with ByVal keyword. And make sure that the string you supplied is long enough to accept whatever data the procedure returns.

Pass an entire numeric array by passing the first element of the array by reference. You can pass an entire user-defined type as a single argument if you pass it by reference. You can’t pass user-defined types by value. When passing a user-defined type that contains binary data, be sure to store the binary data in a variable of an array of the Byte data type.

A null pointer is a pointer to nothing; null pointers have a value of zero. If you need to pass a null pointer to a DLL procedure, declare the argument with the As Any keyword and pass the expression ByVal 0&. A Null is represented by the symbol "0&" or vbNullString.

A handle is a unique long value defined by Windows and used to refer to objects such as forms and reports. When a procedure takes a handle as an argument, always declare it as a ByVal Long. DLL functions that return a handle can be declared as Long functions. Handles are identifier (ID) numbers, not pointers or numeric values. You should never perform mathematical operations on handles.

You can’t pass an object variable to a DLL procedure.

When passing a callback function, using AddressOf procedurename. The procedurename must represent a procedure in a standard module.

Summary:

C-language declaration Visual Basic equivalent Call with

Boolean ByVal B As Boolean Any Integer or Variant variable

Pointer to a string (LPSTR) ByVal S As String Any String or Variant variable

Pointer to an integer (LPINT) I As Integer Any Integer or Variant variable

Pointer to a long integer (LPDWORD) L As Long Any Long or Variant variable

Pointer to a structure

(for example, LPRECT) S As RECT Any variable of that user-defined type

Integer (INT, UINT, WORD, BOOL) ByVal I As Integer Any Integer or Variant variable

Handle (32-bit) ByVal H As Long Any Long or Variant variable

Long (DWORD, LONG) ByVal L As Long Any Long or Variant variable

Pointer to an array of integers I As Integer The first element of the array, such as I(0)

Pointer to a void (void *) V As Any Any variable (use ByVal when passing a string)

Void (function return value) Sub procedure Not applicable

NULL As Any ByVal Nothing or vbNullString or ByVal 0&

ByVal variable As String

·        ByVal variable As Long

·Char ByVal Ch As Byte Any Byte or Variant variable

·Pointer to a char Ch As Byte Any Byte or Variant variable

·MSDN, "Using Dynamic-Link Libraries"

·Article ID: Q118643 HOWTO: Pass a String or String Arrays Between VB and a C DLL

·Article ID: Q106553 HOWTO: Write C DLLs and Call Them from Visual Basic

Article ID: Q181578 HOWTO: Callback Visual Basic Functions From a C DLL

 

 

Recordset

MSDN, "Dynaset-Type Recordset Object"

The RecordCount property for a table-type Recordset object contains the number of records in the table. The RecordCount property for any other type of Recordset object contains the number of records that have been actually been visited.

When you first create a non-table-type Recordset object, you have accessed (or "visited") only the first record. RecordCount = 1 or 0. To visit all the records, use the MoveLast method immediately after opening the Recordset object, then use MoveFirst to return to the first record.

Aborted transactions may make the RecordCount property value out of date in some multiuser situations. Compacting the database restores the table’s record count to the correct value.

A snapshot-type or forward-only-type Recordset object is static and its RecordCount property value doesn’t change.

MSDN, "Counting the Number of Records in a Recordset"

If you set LockEdits to True and another user already has the page locked, an error occurs when you use the Edit method. Other users can read data from locked pages.

If you set the LockEdits property to False and later use the Update method while another user has the page locked, an error occurs. To see the changes made to your record by another user, use the Move method with 0 as the argument; however, if you do this, you will lose your changes.

When working with Microsoft Jet-connected ODBC data sources, the LockEdits property is always set to False, or optimistic locking. The Microsoft Jet database engine has no control over the locking mechanisms used in external database servers.

 

Debug windows

Immediate window

·        Automatically opens in Break-mode

·        To evaluate any executable statement

·        To find and change the value of variables and properties.

·        To Query or change the value of a variable while running an application.

Watch Window

·        Add Watch : In Break or Design Mode from the Debug Menu

 

 

 

·        You can watch the expression, breaking when the value of the watch expression is true or breaking when the value changes

 

·        It shows the current watch expression

·        The context column indicates the procedure module(s) in which each watch expression is Evaluated

·        You can edit a value

Locals Window

·        Automatically displays all of the declared variables in the current procedure scope and their values.

Calls Stack lists all active procedure calls in the Application that where started but not completed. You can only display the Call stack window when the application is in break mode.

 

TreeView Control

Nodes

·        There can be only one Root node from which all nodes descend.

·        Each node in a tree is a programmable Node object that belongs to the Nodes Collection

·        Each node has a unique index and key property that allows access to the properties of the node.

·        Each node can be a child or parent depending on its relationship to other nodes.

·        To Add a node to a tree use the add method which includes two arguments (relative and relationship). Relative names a node. Relationship specifies the relationship between the new node and the node named in relative.

·        A second way of adding a Node is to declare on object variable

·        A node object can contain images and text

Hittest

·        Returns a reference to the ListItem object or Node object located a the coordinates of x and y.

·        Used with drag-and-drop operations

·DropHighlight

·        Is used in combination with HitTest method in drag and drop operations

·        As the cursor is dragged over a ListItem or Node object the HitTest method returns a reference to any object it is dragged over.

·        The DropHighlight property is set to the hit object. It highlights the hit object with the system highlight color.

·For example: Sets the DropHIghlicht property to the object hit with the HitTest method.

·        Private Sub TreeView1_DragOver_

(Source As Control, X As Single, Y As Single State As Integer)

Set TreeView1.DropHighlight = TreeView1.HitTest(X,Y)

End Sub

 

Late and Early Binding

Late Binding is for generic declaration via Early Binding for specific declaration.

When you declare a variable As Object (or Variant, Form, Control), Visual Basic cannot determine at compile time what sort of object reference the variable will contain. Therefore, Visual Basic must use late binding to determine at run time whether the actual object has the properties and methods you call using the variable.

Early binding uses DispID binding or vtable binding. If Visual Basic can tell at compile time what object a property or method belongs to, it can look up the DispID or vtable address of the member in the type library. There’s no need to call GetIDsOfNames.

Property

 

The ambient property BackColor is suggesting which color a well-behaved control should use as its background color. Some ambient properties are standard, while others are specific to certain containers.

If the NegotiateMenus property of a form is set to True, then the form will share space with the menus of an active object on the form. The NegotiateMenus property is avaiable at design time only.

The Instancing property

All values of the Instancing property besides PublicNotCreatable and Private define externally creatable objects. If the Instancing property of a class is PublicNotCreatable, objects of that class are called dependent objects.

Private objects are only for use within your component.

PublicNotCreatable means that other applications can use objects of this class only if your component creates the objects first. Other applications cannot use the CreateObject function or the New operator to create objects from the class.

GlobalMultiUse or GlobalSingleUse: properties and methods of the class can be invoked without explicitly creating an instance of the object.

MultiUse - One instance of component can provide any number of objects created.

SingleUse- Every object of this class that a client creates starts a new instance of your component.

 

To move the cursor to the second column of a DBGrid control and make that column current, the Collndex property of the Columns Collection of the DBGrid control must be set to two.

·        DBGrid1.Columns.ColIndex = 2