chapter 2: creating activex code components by นภดล...
TRANSCRIPT
2Chapter :CCCCCCCC CCCCCCC CCCC CCC CCCCCCC
By นภดล กมลวิลาศเสถี�ยร Dept. of Computer Engineering, Pri
nce of Songkla University Source: Mastering Visual Basic 5, M icrosoft Corporation
CCCCCCCCCC Animation: Chapter Introduction Use a class module to create an object wi
thin a Visual Basic project. Create an ActiveX code component that e
xposes properties, events, and methods. Create a client application that uses your
code component. Debug and test your code component. Raise events from your code component.
Outline
Overview Creating Objects in Visual Basic Working with ActiveX Code Compon
ent Projects Testing ActiveX Code Components Using Events
Overview
ActiveX technology lets you assem ble reusable components into appli
cations and services. An ActiveX component is a unit of e
xecutable code, such as an .exe, .dl l, or .ocx file, that follows the Active X specification for providing objects
. It exposes objects that can be use d by other applications.
CCCCC CC CCCCCCC CCCCCCCnt s ActiveX Controls - User interface elements that allow you to
rapidly assemble reusable forms and dialo g boxes
ActiveX Documents ActiveX components that must be hosted
and activated within a client application. ActiveX Code Components Libraries of objects. Client applications cr
eate objects from classes provided by the component. Clients call the properties, me
thods, and events provided by the object.
Advantages of Using Activ eX Code Comopnents
Clearly defined interfaces:
Properties, methods and events exposed by code com ponent in a standard way. Can includedescriptive info rmation and help.
Reduced complexity:
Hide programming complexity from other programmers.
Easier updating: Update things, such as business rules, just in the code
component, not all the applications.
Creating Objects in VisualBasic What is a Class Module? Creating an Instance of a Class Class Module Events Creating Methods Creating Properties Using Property Procedures to Creat
e Properties
CC C CCCCC CCCCCCC?
Purpose: blueprint for an object. Each cl ass module defines one type of object.
For example, you might create an Empl oyee class that has properties such as
Employee.LastName and Employee.FirstName, and methods such as Employee.Hire.
Your application can work with multiple instances of an Employee object.
Creating an Instance of aClCCC
Class modules differ from standard mod ules these two ways.
Class modules must be explicitly creat ed before they can be used.
You can create multiple instances of a class module.
Dim objMyObject1 As Class1Dim objMyObject2 As Class1 Set objMyObject1 = New Class1Set obMyObject2 = New Class1 Animation: Class Instancing
CCCCC CCCCCC CCCCCC
- Build in events: Initialize and Terminate
Private Sub Class_Initialize()'Initialize data.iDept = 5
End Sub
Private Sub Class_Terminate()'Any termination code.
End Sub
Creating Methods
Public Sub ShowDate()MsgBox "Date is: " & Now()
End Sub
Public Function SquareIt (Num As Integer) _As IntegerSquareIt = Num * Num
End Function
Dim Demo1 As Class1Set Demo1 = New Class1Demo1.ShowDatei = Demo1.SquareIt (Num:=5)
Creating Properties
Define public variables or Create public property procedures
within your class module
Using Public Variables to CreatePropertiesDim Demo1 As Class1Set Demo1 = New Class1Demo1.User = "Joe"
CCCCC CCCCCCCC CCCCCCCC es t o Cr eat e Pr oper t i es
Usage– Run a procedure when a property value is changed or read.– Constrain a property to a small set of valid values.– Expose a property that is read-only.
Creating a Property
Assigns a string value and retur ns the value for the User proper
ty.
Private gsUser As String
Public Property Let User (s As String)gsUser = Ucase(s)
End Property Public Property Get User () As StringUser = gsUser
End Property
CCCCCCC CCC CCCCCCCCCC C CCoperty This code creates an instance of Class
1 , and sets and retrieves the User property:Dim Demo1 As Class1Set Demo1 = New Class1Demo1.User = "Joe" 'Calls Let procedure.Print Demo1.User 'Calls Get procedure.
A property that returns a standard data type
, define Property Get and Let . A property that is an Object data type , defin e Property Get and Set.
Demonstration CC CCC CC C reate and Use Classes
Working with ActiveX Code Component Projects
- - - In Process vs. Out of Process: DLL v s. EXE
Project Properties Class Module Properties -- Compiling a Component > .dll or .
exe file -- Registering a Component > Using
REgsvr32.exe
Testing ActiveX Code Components Setting Up a Test Project: Testing an
ActiveX DLL or EXE Setting a Reference to a Type Library Debugging a Component - Raising Run Time Errors Demonstration of how to create and t
est a basic code component
- Raising Run Time Errors
To pass an error back to a client ap plication, use the Raise method in
a component.
ERR.Raise (Number, Source, Description, HelpFile, HelpContext)
Component Code
Dim localSalary As Single
Public Property Let Salary(ByVal newSalary As Single) If newSalary < 0 Then Err.Raise 12345 + vbObjectError, , "Salary must be positive" Else localSalary = newSalary End IfEnd Property
Public Property Get Salary() As Single Salary = localSalaryEnd Property
Client Code
Private Sub Command1_Click() Dim x As Company.Employee On Error GoTo HandleError Set x = New Company.Employee x.Salary = -50 MsgBox x.Salary Exit SubHandleError: If Err.Number = 12345 + vbObjectError Then MsgBox "Salary must be positive." End IfEnd Sub
Br eaki ng on Er r or s
Break on All Errors Break in Class Module Break on Unhandled Errors
Using Events
Code components use events to notify c lients that an action has occurred.
For example, a client may want to be no tified when a database value has chang
ed or when a message has arrived.
This section includes the following topics: Adding Events to a Class Handling Events in a Client
Adding Events to a Class
Declaring an EventPublic Event Status(ByVal StatusText As String)
Raising an EventPublic Sub SubmitOrder() 'Method to simulate processing an order. RaiseEvent Status("Checking credit...") 'Simulate credit check delay. EndTime = Timer + 2 Do While Timer < EndTime DoEvents Loop
Adding Events to a Class
Raising an Event (cont’d)
RaiseEvent Status("Processing Order...") 'Simulate processing. EndTime = Timer + 2 Do While Timer < EndTime DoEvents LoopEnd Sub
Handling Events in a Client Declare a WithEvents variable
• Dim WithEvents Order As Project1.Class1
Create an event procedure to handl e the event.
• Private Sub Order_Status(ByVal StatusText As String)
• Debug.Print StatusText• End Sub
Create an instance of the class that is defined with the WithEvents varia
ble.• Private Sub Command1_Click()• Set Order = New Project1.Class1• Order.SubmitOrder• End Sub
Demonstration of How to C reate and Use Events
Lab: Cr eat i ng Act i veX Cl i enCC Exercise 1: Creating a Code Compo
nent Exercise 2: Debugging and Error Ha
ndling Exercise 3: Defining and Using Eve
nts Exercise 4: Compiling and Registeri
ng the Component
The CreditCard Object
Name TypeCardNumber PropertyExpireDate PropertyPurchaseAmount PropertyApprove Method
Assessment For the first three questions, give the correct answers
with explanations.4. Explain the difference between a class and an
object.5. Think of a problem that a class module can be
used to solve it. Specify properties, methods and events that the class may contain.6. Explain the process of handling errors from an
ActiveX code component to a client application.7. Give an example of situations when an ActiveX
code component need to raise an event to its client application. Provide code samples that raise an event on the code component side and handle the event on the client side.
Lab Report
Your lab report should contain the following things:
1. Answers to assessment questions. For the first three questions, give the
correct answers with explanations. 2. Complete code of exercise 1, 2 ,and 3 with explanations of the statements in the code.