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 Event … RaiseEvent… 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 events – RaiseEvent - 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
·The AutoRedraw property is central to working with the following graphics methods: Circle, Cls, Line, Point, Print, and PSet. When set to FALSE (Default), Disables automatic repainting of an object and writes graphics or text only to the screen.
AutoRedraw = False only affects line, pset, circle created at run-time, not design time.
Use Refresh instead of AutoRedraw to save system resources.
Method
The FindFirst method will allow a user to quickly search for the first occurrence of a record in either a Dynaser-type or Snapshot-type recordset by accepting an argument resembling a WHERE clause in a SQL statement. The Seek method requires indexed searchable column. The Move method will sequentially test each record in the recordset.
MS MAP and Practical Questions
Design Issues
AutoRedraw (Applies to), PSET, PRINT method
On a form AutoRedraw is set to False. On the form are the following controls:
Commandbutton, Bitmap in imageControl, Artwork drawn with the Pset method,
text by using the print method of the form. Form is minimized and then restored.
Which two are displayed?
A. Commandbutton *
B. Bitmap in imageControl *
C. Artwork drawn with the Pset method
D. Text by using the print method of the form
You create a form that contains graphics and text. You want to ensure that the form will be automatically repainted after it is resized or is listen by another object.
A. Use the Refresh method to repaint the form
B. Use a paint event procedure to repaint the form
C. Set visible property of the form to true
D. Set the autodraw property of the form to true *
AutoRedraw = False only affects line, pset, circle created at run-time, not design time.
Use Refresh instead of AutoRedraw to save system resources.
Windows takes care of redisplaying the window and controls. But your Visual Basic application must handle redisplaying graphics in a form or picture box.
Setting BackColor will
eliminate all graphics include persistent ones (AutoRedraw=True)
Graphics methods in the Form_Load event are ignored unless AutoRedraw is
set to True
Q: You have two text boxes Text1 and Text2. the Tab index of text1 is set to 0. what will happen when u set the tab index of text2 to 0?
A: Tab index of text1 is set to 1
Design and create forms.
· Create an application that adds and deletes forms at run time.
· Use the Forms collection.
·Which code fragment is proper use of the Forms collections?
A. Dim form1 As Form *
For each form1 in Forms
MsgBox form1.Caption
Next Form1
B. Dim form1 As Form
For each form1 in Forms
MsgBox Forms.Item(form1).caption
Next Form1
C. Dim form1 As Form
For each form1 in forms
Msgbox form1.remove
Next Form1
D. Dim form1 As Form
For each form1 in Forms
Msgbox form1.add()
Next Form1
Which property is only valid for a collection object?
A. UBOUND
B. LBOUND
C. Count *
D. Index
What are the benefits of
Forms collection?
- Allows faster unloading of all forms in the project *
- Faster access
- Standardized mechanism for tracking multiple instances of a form *
- Group forms & drag the group
The For Each...Next statement is useful for enumerating a collection.
You can’t add or delete a Form object from the Forms collection.
You can refer to an individual Form object in the Forms collection either by referring to the form by name, or by referring to its index within the collection.
The Forms collection is indexed beginning with zero.
The Forms collection has a single property, Count, that specifies the number of elements in the collection.
Default firing order of events of a form?
A. Load, Initialize, Resize, Paint
B. Load, Initialize, Paint, Resize
C. Initialize, Load, Resize, Paint *
D. Initialize, Load, Paint, Resize
Start from Main, contain form1, Form1.caption = "blah". Which events will be triggered?
A. load
B. initialize
C. initialize, load *
D. initialize, load, activate
How do you dynamically load controls :
Load object_name
Q: What is the sequence in
which the events in the form will trigger
A: Initialize, Load, Resize, Activate, Paint
Initialize Execute custom property or method, reference a control
Load Execute built-in property or method (except Show) of form/control
Show Form as startup object, or use Show method
Dim x As Integer
What event gets fired?
Initialize
Which control can you
place directly on an MDI-Form?
- Image
– Richtext Box
– Picture Box *
- Hscrollbar
- Option Control
- Frame
The PictureBox, Data controls, Timer controls and Menu controls are the only standard Visual Basic controls that you can place in the internal area of an MDI form.
Form1 contains a command button control that has code in one of its events. To cut the control from form1 and than paste the control onto form2. Where is the event located?
A. It is in the same event of the command button control of form2
B. It is in a different event of the command button control on form2
C. It is deleted when the command button control is cut from form1
D. It is in the General object procedures of form1 *
ProgressBar with visible property set true. To display progress of a lengthy operation in you application. Which property will you set?
A. value *
B. width
C. max
D. index
The Max and Min properties set the limits of the range. The Value property specifies the current position within that range. Actually, the Value property just likes a TAB determining when to display the next chunk.
·
Implement drag-and-drop operations within the Microsoft
Windows® shell.
DragOver Event
·DragOver Form1 to change color of label1
A. Target.color = true
B. Source.color = true *
C. DragLabel.color = true
D. DragControl.color = true
Form1 allow dragging Label1. Which line code use in DragOver event of Form1 to change bg color of Label1 to red?
A. Target.BC = vbRed
B. Source= vbRed *
C. DragLabel= vbRed
D. DragControl= vbRed
Which OleDragOver event parameter indicates dragging onto or away from a target object?
A. effect
B. state *
C. index
D. data
Copy picture from
picturebox control to other app which prop use?
A. oledropMode of the picturebox control
B. oledropMode of the form containing pictureBox control
C. oledragMode of the picturebox control *
D. oledragMode of the form containing pictureBox control
· Determine when to use a specific event.
·You want to trap a function key in a textbox. - Use the Keydown event.
A textbox to allow only numeric entries. - Use the Keypress event.
The KeyPress event uses one argument, keyascii.
For example: How to prevent the text box from receiving any characters other than digits?
Private Sub txtEnterNums_KeyPress (KeyAscii As Integer)
If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
KeyAscii = 0 ' Cancel the character.
Beep ' Sound error signal.
End If
End Sub
· Add code to the appropriate form event, such as Initialize, Terminate, Load, Unload, QueryUnload, Activate, and Deactivate.
·Form1 and Form2 place code in the Terminate event of Form1. Which code to add in order to cause the Terminate event of Form1 to occur from Form2?
A.
F1.Click unload F1
B. F1.hide F1.close
C. unload F1 set F1=nothing *
D. unload F1 end
You have a Label1 on an UserControl1, what event for Label1 to be stretched during design time?
A. UserControl_Initialize
B. UserControl_Resize
C. Label1_Initialize
D. Label1_Resize *
Q: You have a Label
Control in USERCONTROL. If the user resizes the usercontrol during
run-time, in which event will u handle the resizing of the label (so as
to view the Label control)?
A: USERCONTROL_RESIZE
How do you find out if F2 is being pressed?
A. Click
B. Validate
C. KeyDown *
D. KeyPressed
Your form contains a command button control named Command1. The index property of command1 is set to 0. You want to load a second instance of the command button that has its index property set to 1. Which line should you use?
A. load command1.1
B. load command1(1) *
C. load command1.index = 1
D. load command1.index (1)
·
Add a menu interface to an application.
· Dynamically modify the appearance of a menu.
· Add a pop-up menu to an application.
· Create an application that adds and deletes menus at run time.
· (NegotiateMenu) Shortcut Keys
·Combine menu controls of object1 with the existing menu on form1
·A. form1.NegotiateMenu = true *
·B. form1.NegotiatePosition = true
C. object1.NegotiateMenu = true
D. object1.NegotiatePosition = true
Using the NegotiateMenus property, you determine if the menu bar of a form will share (or negotiate) space with the menus of an active object on the form.
If you uncheck the Visible property for a menu item, the menu items below will move up to fill the empty space.
How to attribute Access Keys to menus? &Save
What can you do with a dynamic menu?
A. You can add function
keys to it
B. You can add pop-up menus to it *
C. You can deleted it after creating it *
D. You can create it from the Menu Editor
How to allow menu items to be added at runtime?
A. redimension the menu control array
B. use the add method *//dynamic menu
C. use the load statement
D. set up the menu with blank spaces initially and change at runtime
Q: How will you allow users to edit your control at design time?
A: Set the EditAtDesignTime property of your UserControl object to True.
Q: How do you make your UserControl Object Invisible at run-time?
A: Set the InvisibleAtRuntime property of the UserControl object to True.
Menu control: Which property can only be changed during design time?
- visible
- caption
- checked
- shortcut *
·
Implement user interface controls in an application.
· Display data by using the TreeView control. DropHighLight property
·How to refer to the contents of the child of the selected node of a TreeView?
·Set nodChild = TreeView1.Nodes(TreeView1.SelectedItem.Index).Child
· tvwMyTree.Nodes(10).Children ‘ return the number of children
·tvwMyTree.Nodes(10).Parent.Text ‘ return the Text of Parent
Display Icon for each item in the hierarchy of the website?
A. Outline
B. Listbox
C. Listview
D. Treeview *
A TreeView control displays a hierarchical list of Node objects, each of which consists of a label and an optional bitmap. A TreeView is typically used to display the headings in a document, the entries in an index, the files and directories on a disk, or any other kind of information that might usefully be displayed as a hierarchy.
You are writing code for a Drag and Drop operation. You want to set the DropHighLight property to highlight the target TreeView control element?
A. HitTest *
B. Drag
C. TextHeight
D. StartlabelEdit
The DropHighlight property is typically used in combination with the HitTest method in drag-and-drop operations for TreeView and ListView Controls.
You use the add method of the TreeView control, which parameter can you use to control the creation of a child node?
A. Key
B. Text
C. Relative *
D. Relationship
Relative names a node.
Relationship specifies the relationship between the new node and the node named in relative.
· Display items by using the ListView control.
·How to add the column to a ListView? MyListView.ColumnHeaders.Add ,, "MyNewCol"
·The ListView control displays items using one of four different views ( Large (standard) Icons, Small Icons, List, Report ). You can arrange items into columns with or without column headings as well as display accompanying icons and text.
· ListView1.View = lvwReport
·A unique feature of the Report view is ColumnHeader objects. The ListView control contains a collection of ColumnHeader objects in the ColumnHeaders collection.
What properties can you set while using the Add property for a list view?
· ColumnHeader object.Add(index, key, text, width, alignment, icon)
· Provide controls with images by using the ImageList control.
·For which control does the ImageList control act as a central repository of images? ListImage
·An ImageList control contains a collection of ListImage objects, each of which can be referred to by its index or key.
Dim pnlX As Panel
Set pnlX = StatusBar1.Panels.Add() ' Add a new Panel object.
Set pnlX.Picture = ImageList1.ListImages(1).Picture ' Setting Picture must use set.
TreeView1.ImageList = ImageList1 ' Specify ImageList
TreeView1.Nodes(3).Image = 1 ' Use Index property of ImageList1.
TreeView1.Nodes(3).Image = "image 1" ' or Use the Key property "image 1."
· Create toolbars by using the Toolbar control.
·What Property will you use to access BUTTONS of TOOLBAR? Key & Index
·Toolbar control consists of Button Collection and other controls. The ButtonClick event occurs whenever a button (except buttons with the placeholder or separator Style Property) is clicked. You can identify the button that was clicked by its Index property or its Key property.
· Display status information by using the StatusBar control.
·Which StatusBar property allows the display of common data such as date, time etc?
·A. Text
B. Style *
C. Object
D. SimpleText
A StatusBar control consists of up to 16 Panel objects, each of which can contain text and/or a picture. Properties to control the appearance of individual panels include Width, Alignment (of text and pictures), and Bevel. Additionally, you can use one of seven values of the Style property to automatically display common data such as date, time, and keyboard states. SimpleText property is for Single Panel.
· sbrDB.SimpleText = "Getting records …"
·sbrDB.Style = sbrSimple ' Simple style.
sbrDB.Refresh ' You must refresh to see the Simple text.
Statusbar SB1 Second panel set key property to panel2
Which display the message "blah" in second panel
A. SB1.(2)Text = ..
B. SB1.panels(2).text = .. *
C. SB1.Panels.(panel2).text = ..
D. SB1.PanelItems("panel2").text = ..
· Create an application that adds and deletes controls at run time.
· Use the Controls collection.
· object.Controls.Count
·object.Controls(index)
·If the component is a Visual Basic module, such as a Form or UserControl, you don't have to supply the object expression when writing code within the module. If the container is a compiled ActiveX control, such as a ToolBar control, however, you must always supply the object expression.
· MyForm.Controls(6).Top = MyForm.Controls(5).Top + increment
·== MyForm(6).Top = MyForm(5).Top + increment
· object.Add (ProgID, name, container)
·If you intend to add a user control or any ActiveX control to your form, you must either add the control to the Toolbox, or add its License key to the Licenses collection.
· Option Explicit
·Private WithEvents extCtl As VBControlExtender
Private Sub Form_Load()
Licenses.Add "project1.WeeksCtl", "xydsfasfjewfe"
Set extCtl = Form1.Controls.Add("project1.WeeksCtl", "ctl1")
extCtl.Visible = True ' The control is invisible by default.
End Sub
The For Each ( In Controls )...Next statement is useful for enumerating a collection.
The Panels collection is a 1-based array of Panel objects since, by default, there is one Panel object on a StatusBar control.
Predefined collections such as Fields and Forms are 0-based. User-defined collections declared as New Collection are 1-based.
DBGrid's column collection is 0 based.
An ActiveX control created with Visual Basic is always composed of a UserControl object, plus any controls — referred to as constituent controls — that you choose to place on the UserControl.
Coding Issues
·
Declare a variable.
· Define the scope of a variable by using the Public, Private, and Static statements.
·Q: When should you use public variables instead of property procedures for read-write properties?
·A: The property is a String data type, and there is no constrain on the size or value of the string.
· Use the appropriate declaration statement. ParamArray
·Correctly use of ParamArray keyword?
·- At the end of the (……. As….. , ……As ……, Param Array )
- And not in combination with the Optional keyword
-
You have a variable x. You use the Watch window to see the contents of x. At one time the value of x=100 and the next step is says. It has occurred when the 1 process was finished and the second process was started. How was x declared?
A. Local to 1st procedure *
B. Local to 2end procedure
C. Public in a procedure
D. Public in the General declaration section of the form
Procedure in class module
visible to the project not to other application
A. private function Report1 as bool
B. private function Report1() as bool
C. public function Report1() as bool
D. friend function Report1() as bool *
A variable is declared as Public in a form. From where can the Variable be referenced?
A. Only from other procedures in the same form.
B. Only from forms in the same project
C. From anywhere in the same project, use full qualified name ( Form1.var_name) *
D. From modules in other project
· Write and call Sub and Function procedures.
· Write and call Sub and Function procedures by using named arguments or optional arguments.
· Write and call Sub and Function procedures that require an array as an argument.
· Call procedures from outside a module.
·
Create and use a class module.
· Add properties to a class.
·
·Which two elements are supported in the definition of property procedures
·- optional argument *
·- address of operator
·- alias keyword
- paramArray keyword *
The arglist argument has the following syntax and parts:
[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]
· Add methods to a class.
· Identify whether a class should be public or private. (Global MultiUse).
· Declare properties and methods as Friend.
·You want a procedure to be visible only to objects in the current project. You want that this procedure should be accessible by external clients. How will you declare the Procedure?
·A. Private
B. Friend
C. Public
D. Static
· Set the value of the Instancing property.
· Implements. WithEvents to sink events. AddressOf operator
·How can you create a read-only property Private and a write-only property Public. Which of the following are true?
· A. Private Property Get Name() As String *
·Name = txtname.text
·End Property
·Public Property Let Name(ByVal NewName as String)
·TxtName.text = NewName
PropertyChanged "Name"
End Property
B. Public Property Set Name() As String
· Name = txtname.text
·End Property
Private Property Let
Name(ByVal NewName as String)
TxtName.text = NewName
PropertyChanged "Name"
End Property
C. Public Property Let
Name() As String
Name = txtname.text
End Property
Public Property Set
Name(ByVal NewName as String)
TxtName.text = NewName
PropertyChanged "Name"
End Property
You have to indicate the property changes
for an object. Which of the following is best suited for the above
scenario?
A. Property Get
B. property Let
C. Public Sub() *
D. Public Function()
How can you create a read-only property for a class?
A.
Define a Property Get procedure
and define a Property Let procedure with no arguments.
B. Define a Property Get procedure and a Property Let procedure.
C. Define a Property Get procedure without a Property Set or Property
Let procedure. *
D. Define a Property Set or Property Let procedure without a Property
Get procedure.
How can you create a read-only property?
A. Omit the Property Let procedure *
B. Omit the Property Set procedure
C. Set its ReadOnly property to true
D. Use the Private keyword when declaring the procedure
What are the two restrictions on how the Implements statement can be used?
A. It requires a reference to a type Library *
B. It can be used only once in an application
C. It cannot be used in standard module *
D. It cannot be placed in the general declaration section of a module
The Implements statement can't appear in a standard module. A type library containing abstract interfaces provides a reference point for both implementing and using interfaces. In order to implement an interface, you must use the References dialog box to set a reference to the type library. This is because the type library contains the information required to specify the arguments and return types of the interface's members. In similar fashion, any application that uses objects which have
Q: What is the purpose of the Implements keyword?
· A: The Implements keyword is used to create a secondary interface. For instance, if your application has a reference to a type library that describes the IGrowth interface, you could create a secondary interface in a class module using "Implements IGrowth".
You want to create an instance of an ActiveX component that can Asynchronously signal projects that use it. What should you create? (Choose two)
A. an event
B. an object callback *
C. the Addressof Operator *
D. the Implements statement
Create class module that will be used by other programmers in your company.
-Class must function like an intrinsic feature of VB
-You do not want to require the programmers to write code to create an instance of the class.
Which type of Instancing should you use for the class module?
A. private
B. multiUse
C. GlobalMultiUse *
D. PublicNotCreatable
Sink the events of class1. How define a variable MyVar
A. Dim MyVar as object
B. Dim MyVar as Variant
C. Dim MyVar as new Class1
D. Dim WithEvents my as class1
*
Q: Where and why to use
Friend methods and properties
A: The combination of public to classes in the same project and private
to the external.
·
Access data by using the data controls and bound controls.
·You have a Data Control with Bound Controls. You want to provide the ability to abort changes in the record currently being edited and to refresh the bound controls. How?
Only invoke the UpdateControls method for the Data control.
UpdateRecord Updates database (recordset) with data from bound controls.
UpdateControls Updates database (recordset) changes to bound controls.
Refresh Creates a new recordset based on data control properties.
Update Update recordset with data from bound controls or through code.
Your application has just deleted a record from a dynaset-type Recordset. What is the current record? The delete record.
Which properties of the data control can be changed at run time?
Recordset, databasename, recordsource
· Add data to a table by using the DBList or DBCombo control.
· Add data to a table by using the standard ListBox control.
· Q: A list-box is used as a constituent control. The design window is closed and the control inserted on a form in another project. The user then sets the sort property of the control which in turn sets the sort property of the control. Why does the error occur?
·A: Compile the control project ?
·U have Form,a FRAME & ListBox inside frame. If u set SORT property of Listbox at design time, what will happen.
· box.List(index)
·box.RemoveItem index
box.AddItem item[, index]
· Display information by using the DBGrid control.
·DBGrid is a collection of Column objects. The DBGrid control depends on two other objects:
· The Recordset object of the data control
· The Columns collection of the DBGrid itself
·Each cell of a DBGrid control can hold text values, but not linked or embedded objects.
· Add a data control to a new form, and set its DatabaseName and RecordSource properties to the database and table you want to display.
· Add a DBGrid control to the form, and set its DataSource property to the data control you just created. The DBGrid column headers set automatically from a Data control's Recordset object
· .
Q: How to set properties for the individual Column objects?
A: You must make the DBGrid control UI-active: Select the right mouse button, and choose Edit. Then use pop-up menu.
Q: How to remove column header?
A: object.ColumnHeaders = False
Q: How to refer a colmun?
A: object.ColIndex [= value]
This property returns the zero-based index of a column within the Columns collection.
Q: How to check the value of a specific field in the current record?
A: MyString = Data1.Recordset.Fields("Title").Value
The data in the currently selected row can be accessed using the Bookmark property, which provides access to the underlying Recordset object’s current record.
EOFAction and BOFAction are properties of the data control that determine what happens when you move past the beginning or end of the data control’s recordset.
· Display information by using the MSFlexGrid control.
·Some features
· Read-only data binding.
· Ability of each cell to contain text, a picture, or both.
· Find and replace functionality for complex strings.
·Possible Uses
· sorting and merging data
· spreadsheet with in-cell editing
· outline-style display
·
Access data by using code.
· Navigate through and manipulate records in a Recordset.
· Add, modify, and delete records in a Recordset.
·
·You have 2 tables based upon
which reports are to be generated by making use of a common Field. The
existing Table structure and Report definitions should not be changed.
Which of the following is most appropriate.
A. create a new table and use Filter
B. Create a new table and use Sort
C. create a new Dynaset using Filter*
·Dynaset is default Recordset.
To update the information in a database, your database and recordset must be updatable. To determine this, examine the Updatable property of the database and recordset. To check the ability of a field to accept changes, you will need to examine the Attributes property and test the dbUpdatableField bit.
Add New Record:
Data1.Recordset.AddNew ' Create a new record.
Data1.Recordset("PubID") = 43' Set the field values.
Data1.Recordset.Update ' Append new record.
Edit Exist Record:
Data1.DatabaseName = "Biblio.mdb"
Data1.RecordSource = "Titles"
Data1.Refresh ' Open the database.
Data1.Recordset("PubID") = "12345" ' Change the value.
Data1.Recordset.Update ' Save the changes.
· Find a record in a Recordset.
·Which type of recordset you will use to populate country names into a ListBox? Forward-only
·Which recordset you will use to find a record in multi-user environment? Dynaset
MSDN, "Using Recordset Objects"
· Use the Find or Seek method to search a Recordset. LockEdits
·To locate specific records you can use the Find methods with dynaset- and snapshot-type Recordset objects, and the Seek method with table-type Recordset objects.
· recordset.{FindFirst | FindLast | FindNext | FindPrevious} criteria
·criteria
·A String used to locate the record. It is like the WHERE clause in an SQL statement, but without the word WHERE.
The Seek method works only with table type recordsets, because Visual Basic uses the table’s current index
· table.Seek comparison, key1, key2 ...
·For example: change Record ID 1 to 2
· Dim MyTable As Recordset
·Set MyTable = Data1.Recordset ' Set table-type Recordset variable.
·MyTable.Index = "Supplier ID" ' Define current index.
MyTable.Seek "=", 1 ' Seek record.
Do Until MyTable.NoMatch ' Until no record is found.
MyTable.Edit ' Enable editing.
MyTable("Supplier ID") = 2 ' Change Supplier ID.
MyTable.Update ' Save changes.
MyTable.Seek "=", 1 ' Seek next record.
Loop
Your application uses a data bound control, which action can trigger the Validate event?
A. The user moves to another record *
B. The user invokes the edit method
C. The user invokes the refresh method
D. The user moves focus to another control
Q: What event will be fired when you move from one record to another in a recordset?
A: Update
Validate Event (Data Control)
Occurs before a different record becomes the current record; before the Update method (except when data is saved with the Update Record method); and before a Delete, Unload, or Close operation.
Q: Data control's default Recordset type
A: dynaset-type Recordset
When will Recordcount
property contain accurate count of total number of records in a dynaset
type recordset?
A. immediately after RS is created
B. after every row accessed *
C. when the absolute position property of RS is set to true before RS is
created
D. at all times
Q: Why would you want to set the LockEdits property to False?
A: Optimistic locking is in effect for editing. The 2K page containing the record is not locked until the Update method is executed.
What kind of error is the most expected with optmistic lock?
Data changed; operation stopped
If recordset.lockedits=false, which would be the most like to occur:
A. update error: record locked on <machine_name> by <user_name> *
B. save error: record locked on <machine_name> by <user_name>
C. can not read database...
·
Incorporate dynamic-link libraries (DLLs) into an application.
· Declare and call a DLL routine.
·MSDN, "DLL for Beginners" *****
·
·Q: How to declare a DLL with a
C Char datatype?
A: ByVal variable As Byte
Declare Function
Publicname Lib "libname" [Alias "alias"] [Arguments List] As Type
Empty value ByVal 0&, vbNullString
Char ByVal a As Byte
Asciiz String ByVal as String
· Identify when it is necessary to use the Alias clause.
· Create a DLL routine that modifies string arguments.
· Pass a null pointer to a DLL routine.
· Pass an argument by value and by reference.
· Pass a function pointer to a DLL by using a callback function. Address Of operator
· Pass a string to a DLL.
·There are 2 deferent DLL from 2 vendors and the DLL have the same name. What must you do to be able to call both functions?
A. modify function name in one
B. declare public in separate module use the alias keyword to
C. declare private rename one function *
D. Use the alias keyword to rename one function *
We obtained many DLL functions from different vendors. Two functions happen to have the same name but different purposes. What can we do?
A.
Using an alias *
B. Declaring each Private in separate modules *
C. Registering one with another name
D. Modifying the DLL function.
Pass argument contain
address of a Vb subroutine named MyProc to a MicWind HPL
A. Aressof := MyProc
B. Adressof Me.MyProc
C. Adressof MyProc *
D. Adressof (MyProc)
·
Build a Microsoft ActiveX™ client.
· Use the Dim statement to reference an object.
· Use the Set statement to create an instance of an object.
· Use the CreateObject function to create an instance of an object. GetObject. ActiveX Design
·
·Which code will create a new instance of object named Form1 in Project1?
·A. Dim Frmx As Form1
B. Dim Frmx As New Form1 *
C. Set Frmx = Form1
D. Set Frmx = GetObject("Project1.Form1")
How many instances of class1 after running exist after the following code?
Dim a As Class1
Dim b As new Class1
b.MyProperty = 3
Set a = new Class1
A. 0
B. 1
C. 2 *
D. 3
In which case is a new object created?
set x=new form1
Which Option will not allow to create instances :
set Public to FALSE
·
Create an Automation server that exposes objects, properties, methods,
and events.
· Define properties for objects by using property procedures.
· Create a method that displays a form.
· Create a multithreaded component.
· Use App object properties to control server behavior.
· Call an object server asynchronously by using a callback mechanism.
· Create, use, and respond to events. early binding vs. late binding
·Q: The differences between early binding vs. late binding
·
A: Late binding occurs when the compiler does not know
about an object until run time.
Early binding occurs when Visual Basic knows at compile time exactly
which interface will be used with an object variable.
·Which two required for Early
Binding?
A. Type library *
B. Dual Interface
C. New Keyword *
D. CreateObject Function
For Early Binding
Dim Varnaem as Class
Set varname = CreateObject(ClassName)
·
Create and use an ActiveX control.
· Declare and raise events.
·How to raise an event?
·First to declare it, use the Event keyword, then Raise it.
e.g. RaiseEvent ABC (arguments)
· Create and enable a property page.
· Use control events to save and load persistent control properties.
· Add an ActiveX control to a Web page.
· (esp. ActiveX Controls – CAB/ID/LPK_TOOL/Security – Level in IE/Licensing/ Digital Signing/ Mark as Safe for Scripting/Initialization)
·How Project Groups can be used when debugging ActiveX controls(lots of Qs).
·Ambient & Extender
·What is the property of a container that can be used to change the background color of the control on the container when the background color of the container changes?
·A. Ambient *
·B. Extender
C. Appearance
D. Property Pages
ActiveX controls have three basic categories of control properties: ambient, extender, and custom.
Ambient properties give your control information about the state of its container. Extender properties are those that seem to be part of your control but are actually provided at runtime by the container.
Custom properties are ones that you implement entirely on your own.
How do you create a license package file containing the licensing information for all controls on a Web page?
A.
With the Visual Basic License
Manager.
B. With the CODEBASE parameter of an HTML page's<OBJECT>tag.
C. With the Visual Basic Application Wizard.
D. With a utility from the LPK_TOOL directory on the Visual Basic CDROM.
*
Run-time license:
Application Setup Wizard
Design-time license: Application Setup Wizard
Internet license: LPK_TOOL.EXE, and create a reference to the .LPK file
A Visual Basic application supplies the run-time license to a control
automatically, but this process does not happen with an HTML page. The
license manager supplies the license to the control from the .lpk file.
Q: How to add a control to a web page?
A: By scripting
·
Create and use ActiveX documents.
· Compare ActiveX documents to embedded objects.
· Create an ActiveX project with one or more UserDocument objects.
·The base object of an ActiveX document, the UserDocument object resembles a standard Visual Basic Form object with some exceptions.
·You cannot place embedded objects (such as an Excel or Word document) or an OLE Container control on a UserDocument.
You cannot use the Show method to show ActiveX documents
To navigate between the two ActiveX documents, use the HyperLink object and its NavigateTo method.
· Persist data for an ActiveX document.
·Data persistence is the ability of a component to store and retrieve data. The Internet Explorer 3.0 (and higher) and Microsoft Office Binder allows you to write to a file using the PropertyBag.
· Automate an ActiveX document.
· Add an ActiveX document to a Web page.
· ActiveX Dlls & (ActiveX Document DLL)
·You want to minimize download time for an ActiveX document with several components. How package within a .cab file?
In a single .cab file
One .cab with ActiveX document. And a second .cab with referenced components
One .cab with ActiveX document and an INF file that points to individual cab files for each component. *
One .cab with ActiveX document, an INF file that points to a .cab file with the referenced components
Q: How to reduce the time for downloading on Internet an ActiveX component?
A: Create separate secondary .cab files ???
Users may already have these secondary .cab files on the system or the secondary .cab files can be downloaded from Microsoft's web site.
Which two project types can contain an ActiveX Document?
A. Standard EXE
B. ActiveX Document EXE *
C. ActiveX Document DLL *
D. ActiveX Control
Q: What project types can have ActiveX documents?
A: All that can be a container
Q: How to convert an ActiveX.DLL to multithread?
A: Make it ActiveX. EXE
Q: Advantages of Using ActiveX Documents (Choose 2).
· Support for the Hyperlink object
· Support for the AsyncRead method
The AsyncRead method initiates an asynchronous download.
Datatypes to be downloaded: files, pictures, byte arrays
Q: What elements of ActiveX Components on a Web page contribute to security?
· A: When you use ActiveX controls on a Web page, you can implement the following security measures:
· Set the appropriate level of security in Internet Explorer
· Provide users with information about the author of the control
· Through digital code signing
· Create an Internet download by marking your Controls as safe for scripting and initialization
Which project template
would you select to build an in-process code (ActiveX Document DLL)?
Create applications that can access the Internet.
· Gain access to the Internet or an intranet by using the Hyperlink object.
· Create an application that has the ability to browse HTML pages.
· Create an application that enables connections to the Internet.
·Hyperlink object
Use the NavigateTo method to jump to a URL.
Use the GoBack or GoForward methods to go backwards or forwards through the History list.
WebBrowser Object - Use GoHome and GoSearch
Which 2 actions may disqualify a component for being marked as safe for scripting?
A. the component creates a password
B. the component writes information to a file
C. the component inserts data in registry *
D. the component reads information from registry *
Q: There is a www server
application that uses ActiveX controls you developed. When the
application page is browsed with IE it does not show the ActiveX
control. What may be happening?
A1: No Internet download license file on the web server
A2: Options in the Application Setup Wizard were not used correctly
What ActiveX can do on WWW?
A. create licensing files
B. digital signing
C. register your control on a user’s computer *
D. modifying the users internet security settings
If you want to offer an option in a help menu for users to access your Web Site, what ActiveX Document should you use?
A.
Automation
B. WinSock
C. Hyperlink *
D. ActiveX component
B.
You have an ActiveX document that uses the AsyncRead method to obtain data from an intranet location. What type of data does it cannot return directly?
A.
Files
B. Byte arrays
C. Pictures
D. Hyperlinks *
B.
What is the purpose of the ID parameter in an HTML <OBJECT> tag?
A. Specifies a URL that
points to a file containing an implementation of an object.
B. Specifies the object's unique class identifier stored in the system
registry.
C. Specifies a URL that points to the name of the object.
D. Specifies the object name. *
·
Implement error-handling features in an application.
· Raise errors from a server.
· Create a common error-handling routine.
· Display an error message in a dialog box by using the Err object.
· Use the appropriate error-trapping options, such as Break on All Errors, Break in Class Module, and Break on Unhandled Errors. Out of stack space error
·An ActiveX component connects to a database, the connection to the database fails. What to do?
·A. Create an error event
B. Set err object to false
C. Call raise method of the err object *
C. Create a prop name connected that returns false
Q: An error occurs in a component that you wrote, how to notify client:
A: Err.Raise number
Which property of the Err object returns the name of the object that generated an Error?
A. Description
B. Source *
C. Number
D. Helpcontext
Q: Which code segment would best trap a "division by zero" error handling?
A: For example: (See Error Handling)
·
Public Sub ProcDivZero()
On Error GoTo ErrTrapper
X = 100 / 0
Exit Sub
End Sub
ErrTrapper:
If Err.Number = 11 Then Debug.Print "Division by Zero Found"
End Sub
·When the following code executes. What will the user see?
· Public Sub MyTest()
·On Error GoTo ErrHandler
Dim X as Integer
MyProc(X)
MsgBox "XXX"
Errhandler:
MsgBox "YYY"
End Sub
Public Sub MyProc(X As Integer)
On Error GoTo MyprocErr
X = X / 0
MyprocErr:
MsgBox "ZZZ"
End Sub
a) "XXX" Only
b) "ZZZ" Only
c) "XXX", "ZZZ" and "YYY" Only *
d) "XXX" and "ZZZ" Only
Q: What will be shown when
this code is executed?
Private Sub Command1_Click()
Command2.Value = True
End Sub
Private Sub Command2_Click()
· Command1.Value = True
·End Sub
A: Out of Stack Space error
Q: What will happen if user presses command2?
Sub Mysub()
· Static intNum As Integer
·If intNum <= 4 Then
· Exit Sub
·Else
· intNum = intNum + 1
·Mysub
End If
End Sub
Private Sub Command2_Click()
· Mysub
·End Sub
A: The code will run OK
·
Implement Help features in an application.
· Set properties to automatically display Help information when a user presses F1.
· Use the HelpFile property to set the default path for Help files in an application.
· Use the CommonDialog control to display the contents of a Help file.
·You want to use the ShowHelp method to display specific Help file pages for your application without declaring a dll. Which object?
·A. App
B. Menu
C. MenuLine
D. CommonDialog *
Before you use the ShowHelp method, you must set the HelpFile and HelpCommand properties of the CommonDialog control to one of their appropriate constants or values. Otherwise, Winhlp32.exe doesn't display the Help file.
CommonDialog1.ShowHelp
This requires: CommonDialog1.HelpFile to be set
· CommonDialog1.HelpCommand to be set
·Maybe a reference to CommonDialog1.HelpKey
HelpcontextID set to 0 for an option Button in a Frame, what will happen when press F1?
A. Help conexts page is displayed
B. HelpContextID property of form is evaluated
C. HelpContextID property of the frame is evaluated *
D. Context help for the Option Button control is displayed.
Form’s HelpContextId is searched for non-zero value and if so, help is displayed for the Form
If HelpContextID is set to 0, then Visual Basic looks in the HelpContextID of the object's container, and then that object's container, and so on. If a nonzero current context number can't be found, the F1 key is ignored.
Debugging and Testing Issues
·
Select appropriate compiler options.
· List and describe options for optimizing when compiling to native code.
· List and describe the differences between compiling to p-code and compiling to native code.
·What code will have the most to gain on to be compiled to Native Code?
·A. Code that uses windows API
B. Code that has much String functions
C. Code that manipulates objects
D. Code that have complex Financial calculations *
Your application relies on arguments that are passed by reference. Which two native code compilation options should you select to optimize the performance of numeric processing?
A. Assume no Aliasing
B. Optimize for small code
C. Remove VB floating point error checks *
D. Remove Safe Pentium FDIV checks *
You are creating an application that is intended to run on only PentiumPro based servers. You want to maximize the performance of this application. Which compiler option should you use?
A. Assuming no Aliasing
B. Optimize for small code
C. Create symbolic debug information
D. Remove safe for Pentium FDIV checks *
·
Compile an application conditionally.
· Use the #If…#End If and #Const directives to conditionally compile statements.
· Set the appropriate conditional compiler flags.
·
·You want the code written for debugging should not be compiled. How will you accomplish this?
·A. Use If .. Then .. Else Statements
B. Use the Err Object
C. Use conditional compilation *
D.
Which element can you use in a conditional compilation directive?
A. Public variable
B. Public constant
C. Literal expression *
D. Undefined constant
Creating an application that uses conditional compilation to enable and disable elements of functionality, which two mechanisms can you use to set conditional compilation constants?
A. Dim statement
B. Constant statement
C. #Constant directive *
E. Project property dialog box *
Q: Where do you define conditional compiling variables?
A: Command line
Project Properties dialog box (under the Make tab)
In code
Conditional compiling
could be used to:
1.designing an application to run on different platforms
2.changing the date and currency display filters
3.Remove debug code
What expression is acceptable for #const
Only literal and their operation except Is
·
Set watch expressions during program execution.
·Q: When can you add watch variables?
A: In Break and design mode
Two advantages of using the context options in the Add watch dialog box are.
A. Allow multiple projects scope
B. Allow faster evaluation of expressions by narrowing content (of context) *
C. Increase number of break mode options
D. Viewing variables that have the same name but different scope *
Sets the scope of variables watched in the expression. Use if you have variables of the same name with different scope. You can also restrict the scope of variables in watch expressions to a specific procedure or to a specific form or module, or you can have it apply to the entire application by selecting All Procedures and All Modules. Visual Basic can evaluate a variable in a narrow context more quickly.
·
Monitor the values of expressions and variables by using the debugging
windows.
· Use the Immediate window to check or change values.
· Explain the purpose and usage for the Locals window. (Add watch Window)
·Which variable does the local window show? (select 2)
·A. All variables within a module
B. All variables within your Application
C. All variables within the Current procedure *
D. All object variables within the current scope *
Which task(s) can you perform by using the locals window
A. Edit the call stack
B. Define new variables
C. View and change expressions
D. View and change variables of the current procedure *
Which three task can you perform by using the immediate window in break mode?
A. declaring a variable as object
B. declaring a function
C. executing a function *
D. executing the call stack
E. view the value of the variable *
F. changing the value of the variable *
G.
Immediate window: A control structure is valid only if it can be completely expressed on one line of code, use colons to separate the statements.
You want to find out when a variable changes to a new value. Which tool would you use?
- Watch window
You are observing variable1 in Procedure1 in the Locals Window. Suddenly the Locals Window displays that the variable is "Out of Context" when it enters Procedure2. How was variable1 declared?
A. As a Public in a standard Module
B. As a Private variable in Procedure1 *
C. As a Private variable in Procedure2
D. As a Private variable in the General Section of the Form
·
Implement project groups to support the debugging and development
process.
· Debug DLLs in process.
· Test and debug a control in process.
·You want to test the Unload behavior of an In-Process component. What should you do?
·A. Start another instance of the development environment and create a test project that references the component.
B. Create a project group that contains both a test project and the component *
C. Add debug statements to the DLL component
E. Call the free library function in the MS Windows API
A control to be used by
all programmers in a company. You need debug control: interaction with
the same process as one of your applications. How to do?
A. add control project to your app project *
B. load control project in second instance
C. in the app proj add a reference to control project
D. in the control proj add a reference to app project
· Q: What is the difference between debugging an ActiveX control project and an in-process component?
A: The component code can run while the client is in Design mode
· Q: When testing a UserControl, you add a standard.exe to your project group. UserControl in the Toolbox is dimmed. What should you do?
A: Close the UserControl designer and then test again
What should you do to
debug an out of process component?
A. Start a second instance of the development environment *
B. Compile the component by using symbolic debug information
C. Create an error handler for the out of process component
D. Create a project group
·
Define the scope of a watch variable.
·
How to view contents of the Variant?
A. Use Debug.print *
B. Use Object browser
C. Look at the Locals window *
D. Copy to Clipboard
Distribution Issues
·
Use the Setup Wizard to create an effective setup program.
· Edit the Setup.inf file.
· Edit the Vb5dep.ini file.
·
Create a setup program that installs and registers ActiveX controls.
Manage the Windows system registry.
· Use the GetSetting function and the SaveSetting statement to save application-specific information in the registry.
· Register components by using the Regsvr32.exe utility.
· Register components by using the Remote Automation Connection Manager.
· Edit the registry manually.
· Register a component automatically.
·Save settings?
·A. local_Machine
·B. current_User *
·C. Current_Config
D. Classes_Root
IIS can not instantiate an object provided by the DLL (ActiveX) What should you do to the DLL?
A. Digital Sign it
B. Mark as safe for initialize
C. Mark as safe for scripting
F. Register by Regsvr32 utility *
If you want to install your Visual Basic application in other computer, how do you find out about the components that are registered in that computer?
REGSRV32.EXE
Q: How to use Regsvr32.exe to install ActiveX DLL, EXE, OCX?
A: To install ActiveX.dll - Regsvr32 dllname
To register Activex.Exe - MyActiveX.exe /regserver
To unregister Activex.Exe - MyActiveX.exe /unregserver
Distribute an application over the Internet.
Which task can you accomplish by packaging in .cab file?
A. creating license file
B. digital sign it
C. register on users computer *
D. modifying users internet security settings
Q: What cannot be done when an Internet Control is packaged. (Choose Two)
A: Write to a file
Read from the registry
Q: How can you build ActiveX components for Internet distribution?
A: Use the Application Setup Wizard and pick the appropriate options
Q: What type of files does the Setup Wizard generates for Internet download setup? *.CAB files.
Q: Which function can the Setup Wizard of the Enterprise Edition of VB 5 perform in addition to installing your ActiveX EXE project?
A: install your project as an ActiveX shared component
Q: What does locales show in different contexts?
A: In Visual Basic, many functions use the user's system locale, which uses the Control Panel settings provided by the operating system to automatically determine the conventions at run time. These functions are called locale-aware functions.
Cram Section
1.
1.
1. When AutoRedraw is set to False, Commandbutton, Bitmap are displayed.
For automatically repainted after it is resized, set the AutoRedraw property of the form to true.
VB can automatically arrange Tab index.
Forms collections works best with " For Each … Next "
A collection object has a only Count property.
What is the event trigger sequence? Initialize, Load, Resize, Activate, Paint
The PictureBox, Data controls, Timer controls and Menu controls are the only standard Visual Basic controls that you can place in the internal area of an MDI form.
When cut-paste the control from F1 to F2, the event is still in the General Part of F1.
To set ProgressBar.Value property to display progress of a lengthy operation.
DragOver Form1 to change color of label1 - Source.color = true
DragOver event of Form1 to change bg color of Label1 to red? Source= vbRed
OleDragOver event parameter State indicates dragging onto or away from a target object
Coping of picture from
picturebox control to other app uses oledragMode of the picturebox
control.
You want to trap a function key in a textbox. - Use the Keydown
event.
A textbox to allow only numeric entries. - Use the Keypress (KeyAscii As Integer) event.
Trigger the Terminate
event of Form1 from Form2 - unload F1, set F1=nothing
Function KeyF2 is being pressed - KeyDown
load command1(1) - correct
Using the Form1.NegotiateMenus property to determine how to share the menubar with object.
If you uncheck the Visible property for a menu item, the menu items below will move up to fill the empty space.
How to attribute Access Keys to menus? &Save
With a dynamic menu - You can add pop-up menus and delete it after creating.
To add menu items at runtime – Use the menu control array, the add method
UserControl.EditAtDesignTime property to allow users to edit your control at design time.
UserControl.InvisibleAtRuntime property to set Object Invisible at run-time.
Menu control: shortcut property can only be changed during design time.
A TreeView control displays a hierarchical list of Node objects.
The DropHighlight property is typically used in combination with the HitTest method in drag-and-drop operations for TreeView and ListView Controls.
You use the TreeView1.nodes.add Relative to control the creation of a child node.
How to add the column to a ListView? MyListView.ColumnHeaders.Add ,, "MyNewCol"
A unique feature of the Report view is ColumnHeader objects. The ListView control contains a collection of ColumnHeader objects in the ColumnHeaders collection.
For which control does the ImageList control act as a central repository of images? ListImage
An ImageList control contains a collection of ListImage objects, each of which can be referred to by its index or key.
Set pnlX = StatusBar1.Panels.Add() ' Add a new Panel object.
Set pnlX.Picture = ImageList1.ListImages(1).Picture ' Setting Picture must use set.
What Property will you use to access BUTTONS of TOOLBAR? Key & Index
StatusBar1.Style property allows the display of common data such as date, time, etc.
Insert text to Statusbar SB1 Second panel- SB1.panels(2).text = "text"
UserControl object.Add (ProgID, name, container)
The Panels collection is a 1-based array of Panel objects.
Predefined collections such as Fields and Forms are 0-based.
User-defined collections declared as New Collection are 1-based.
DBGrid's column collection is 0 based.
ParamArray - At the end - And not in combination with the Optional keyword
Procedure in class module visible to the project not to other application – Friend
Public in a form - Can be referenced from anywhere in the same project
Property procedures have optional AND ParamArray keywords.
How can you create a read-only property - Omit the Property Let procedure
The two restrictions on Implements statement - type Library, Not be in standard module
How to use Implement statement - Implement MyServer.MyRule
An ActiveX component can Asynchronously signal projects that use it – callback AND Addressof
Sink - WithEvents
Your application has just deleted a record from a dynaset-type Recordset. What is the current record? The delete record.
Which properties of the data control can be changed at run time? Recordset, databasename, recordsource
The data in the currently selected row can be accessed using the Bookmark property, which provides access to the underlying Recordset object’s current record.
EOFAction and BOFAction are properties of the data control that determine what happens when you move past the beginning or end of the data control’s recordset.
Access 2 tables – by Dynaset using Filter
Which type of recordset you will use to populate country names into a ListBox? Forward-only
Which recordset you will use to find a record in multi-user environment? Dynaset
recordset.{FindFirst | FindLast | FindNext | FindPrevious} criteria . criteria likes the WHERE clause.
table.Seek comparison, key1, key2 ... MyTable.Seek "=", 1
Trigger the Databound Validate event - move to another record
Update event will be fired when you move from one record to another in a recordset.
LockEdits property to False - Optimistic locking - update error
What kind of error is the most expected with optmistic lock? Data changed; operation stopped
Empty value ByVal 0&,
vbNullString
Char ByVal a As Byte
Asciiz String ByVal as String
2 deferent DLLs from 2 vendors - declare private or Use the alias keyword
Adressof MyProc - Correct
In which case is a new object created? set x=new form1
Which Option will not allow to create instances : set Public to FALSE
Type library and New
Keyword are required for Early Binding.
How to raise an event? First to declare it, use the Event keyword, then
Raise it.
Ambient - change the background color of the control on the container
Create a license package file with a utility from the LPK_TOOL directory.
Run-time license:
Application Setup Wizard
Design-time license: Application Setup Wizard
Internet license: LPK_TOOL.EXE, and create a reference to the .LPK file
To navigate between the two ActiveX documents, use the HyperLink object and its NavigateTo method. Use the GoBack or GoForward methods to go backwards or forwards through the History list. WebBrowser Object - Use GoHome and GoSearch
Hyperlink offers a help option on Web.
Data persistence is the ability of a component to store and retrieve data. The Internet Explorer 3.0 (and higher) and Microsoft Office Binder allows you to write to a file using the PropertyBag.
Create separate secondary .cab files to reduce download time.
Which two project types can contain an ActiveX Document? ActiveX Dll, ActiveX Exe.
What project types can have ActiveX documents? - All that can be a container
How to convert an ActiveX.DLL to multithread? - Make it ActiveX. EXE
Advantages of Using ActiveX Documents - Support for the Hyperlink object and AsyncRead method
Which project template would you select to build an in-process code (ActiveX Document DLL)?
The AsyncRead method initiates an asynchronous download.
Datatypes to be downloaded: files, pictures, byte arrays
Which 2 actions may disqualify a component for being marked as safe for scripting? inserts in/reads from registry
ID parameter in an HTML <OBJECT> tag specifies the object name.
When an error occurs in a component, call Err.Raise number.
Err.Source returns the name of the object that generated an Error.
Command1_Click() AND Command2_Click() call each other - Out of Stack Space error
Before you use the CommonDialog.ShowHelp method, you must set the HelpFile and HelpCommand properties.
If HelpContextID is set to 0, then Visual Basic looks in the HelpContextID of the object's container.
Financial calculations will have the most to gain on to be compiled to Native Code.
Optimize the numeric processing performance - Remove VB - Remove FDIV
Literal expression can be used in a conditional compilation directive.
How to set conditional compilation constants - #Constant directive, Project property dialog box
When can you add watch variables? - In Break and design mode
You can restrict the scope of variables in watch expressions to a specific context. Visual Basic can evaluate a variable in a narrow context more quickly.
Locals window - View and change variables of the current procedure
Immediate window - executing a function, view or change ariable
Test behavior of an In-Process component - Create a project group
Debug an out of process component - Start a second instance of IDE
Save settings in – Hkey_current_User
Find out about the components that are registered in that computer - REGSRV32.EXE
To install ActiveX.dll - Regsvr32 dllname
To install Activex.Exe - AX_exename /Regserver
Which task can you accomplish by packaging in .cab file? register on users computer
Q: There is a www server
application that uses ActiveX controls you developed. When the
application page is browsed with IE it does not show the ActiveX
control. What may be happening?
A1: No Internet download license file on the web server
A2: Options in the Application Setup Wizard were not used correctly
Q: Where do you define conditional compiling variables?
Command line
Project Properties dialog box (under the Make tab)
In code
· Q: Difference between debugging an ActiveX control project and an in-process component?
A: The component code can run while the client is in Design mode
· Q: When testing a UserControl, you add a standard.exe to your project group. UserControl in the Toolbox is dimmed. What should you do?
A: Close the UserControl designer and then test again
How to view contents of the Variant?
- Use Debug.print
- Look at the Locals window
Q: What cannot be done when an Internet Control is packaged. (Choose Two)
A: Write to a file
Read from the registry
Q: How can you build ActiveX components for Internet distribution?
A: Use the Application Setup Wizard and pick the appropriate options
Q: Which function can the Setup Wizard (Enterprise Ed.) of VB 5 perform in addition to installing your ActiveX EXE project?
A: install your project as an ActiveX shared component
Q: What does locales show in different contexts?
A: In Visual Basic, many functions use the user's system locale, which uses the Control Panel settings provided by the operating system to automatically determine the conventions at run time. These functions are called locale-aware functions.
Q: When should you use public variables instead of property procedures for read-write properties?
A: The property is a String data type, and there is no constrain on the size or value of the string.
Q: Where and why to use
Friend methods and properties
A: The combination of public to classes in the same project and private
to the external.
Q: You have a Data Control with Bound Controls. You want to provide the ability to abort changes in the record currently being edited and to refresh the bound controls. How?
A: Only invoke the UpdateControls method for the Data control.
· Q: A list-box is used as a constituent control. The design window is closed and the control inserted on a form in another project. The user then sets the sort property of the control which in turn sets the sort property of the control. Why does the error occur?
A: Compile the control project ?
Q: How to set properties for the individual Column objects?
A: You must make the DBGrid control UI-active: Select the right mouse button, and choose Edit. Then use pop-up menu.
Q: How to remove column header?
A: object.ColumnHeaders = False
Q: How to refer a colmun?
A: object.ColIndex [= value]
This property returns the zero-based index of a column within the Columns collection.
Q: How to check the value of a specific field in the current record?
A: MyString = Data1.Recordset.Fields("Title").Value
Data1.Recordset("PubID") = 43' Set the field values.
Data1.Recordset("PubID") = "12345" ' Change the value.
What are the benefits of
Forms collection?
- Allows faster unloading of all forms in the project *
- Faster access
- Standardized mechanism for tracking multiple instances of a form *
- Group forms & drag the group
How to handle resizing of the label in a UserControl?
During design time - Label1_Resize
During run-time – UserControl1_resize
How to refer to the contents of the child of the selected node of a TreeView?
Set nodChild = TreeView1.Nodes(TreeView1.SelectedItem.Index).Child
· tvwMyTree.Nodes(10).Children ‘ return the number of children
·tvwMyTree.Nodes(10).Parent.Text ‘ return the Text of Parent
What properties can you set while using the Add property for a list view?
· ColumnHeader object.Add(index, key, text, width, alignment, icon)
·Which type of Instancing should you use for the class module?
A. private
B. multiUse
C. GlobalMultiUse
D. PublicNotCreatable *
Conditional compiling
could be used to:
1.designing an application to run on different platforms
2.changing the date and currency display filters
3.Remove debug code
Local window shows -
All variables within the Current procedure
All object variables within the current scope
Create class module that will be used by other programmers in your company.
-Class must function like an intrinsic feature of VB
-You do not want to require the programmers to write code to create an instance of the class.