ActiveX
technology was introduced in Visual Basic 5.0 for the first time. Since then it
never looked back. I often hear people talking about ActiveX as some thing that
is related to internet only. And some seem to think ActiveX as an advanced
topic. In my sincere opinion, neither of them is true. Every Visual Basic
programmer must understand what is ActiveX and how to create ActiveX
components. So let us start our journey
of ActiveX. But before we delve into
ActiveX we need to understand the software architecture on which ActiveX is
based – COM.
What is COM?
COM stands for Component Object Model. COM
is software architecture that allows programmers to create components, which
can be later used to build applications. The theme is reusability. To put it in other words, if you create a component
using COM specifications, it can be used in any language and any platform where
COM is supported.
COM is the underlying architecture that
forms the foundation for higher-level software services, like those provided by
OLE and ActiveX.
COM specifies the standards using which
components are to be created. And the components created using COM
specifications have the following characteristics:
They are platform independent. They are
usable in Windows, Windows NT, Macintosh, and Unix. They are language
independent. If you create a component in Visual Basic, later you can use that
component in VC++, PowerBuilder or anywhere, where COM is supported.
They are also extensible.
COM is a general architecture for component
software. Microsoft is using COM to address specific areas like creating
controls, servers etc.
It is beyond the scope of this book to
discuss about the specifications and internals of COM. There are so many technical articles in MSDN
on COM and DCOM. Read them if you want to have an insight of COM.
What is ActiveX?
ActiveX is a new technology (actually a
renamed technology). Its predecessor is OLE ; ActiveX allows you to create
components based on COM specifications and enables you to develop interactive
web pages.
ActiveX includes both client and server
side technologies. That means it allows you to create components that run both
on client and server.
An ActiveX component is a reusable piece of
data and code (object) created using ActiveX technology. The best part of
ActiveX is it allows you to create components that can be used in any project
(irrespective of language) straight away.
This saves a lot of development time. Well, if you boil it down, it
comes to reusability, which is one of the characteristics of component software
to which ActiveX belongs.
However, note that ActiveX talks about binary interoperability. That means only
compiled components are reusable and NOT source code.
ActiveX Components
The components that you create using
ActiveX technology are of different types. The following are the different
types of ActiveX components.
ActiveX Applications (ActiveX .EXE)
An ActiveX application is a standalone
application, such as MS-Word, MS-Excel etc.
These applications provide objects that you can access and manipulate
programmatically from an application written in Visual Basic or any application
development tool that supports ActiveX.
Note: Each component has a collection of properties, methods and events
that can be accessed from outside. These properties, methods and events are
collectively called as interface of the component.
ActiveX Code Components (ActiveX .DLL)
ActiveX code component is a collection
(library) of programmable objects, where objects are generally related to a
specific topic such as, financial functions, date and time functions etc.
ActiveX code components do not run as
separate applications, instead they are run in the same process area as the client
(the application that is using the code component). More on this later in this
chapter.
ActiveX Controls (.OCX controls)
ActiveX controls are user-defined controls.
Formally they were called as OLE controls. Each ActiveX control does a specific
job. For example, an ActiveX control may deal with displaying a calendar,
another may deal with displaying running digital clock and so on. There are hundreds of ActiveX controls
available from various vendors, whose primary job is creating ActiveX controls
and sell them to developers.
Note that even Visual Basic 4.0 users could
create OLE Server (now called as ActiveX Server) but creating an ActiveX
control was introduced for the first time in Visual Basic 5.0. It really made
Visual Basic programmers thrilled. Well, I am one of them and now you join the
bandwagon.
In fact, we have already used good number
of ActiveX controls, such as DataList, ADODC, DataGrid etc. We know how to use
them but in the coming chapters 27, 28 & 29 we will learn how to create our
own ActiveX controls.
ActiveX Document (. VBD Document)
ActiveX documents are Internet pages. You
can use ActiveX documents to create interactive Internet application. Each
ActiveX document is a Web page. An ActiveX document can host ActiveX controls
and can invoke dialog boxes and so on.
Visual Basic 6.0 has introduced DHTML
application. DHTML application provides
better alternative to ActiveX document application.
In-process and Out-of-process servers
An ActiveX code component may be either in-process or out-of-process. In-process
server is implemented as .DLL and out-of-process server is implemented as .EXE.
An application using ActiveX component
interacts with it using Client/Server architecture. Application makes the
request to the component and component responds to the request. Here client is the application that is using
the services of the component. And the ActiveX component is the server.
Depending upon where server runs, ActiveX components are classified into two
types.
In-process server
An in-process server is an ActiveX
.DLL. It runs in the address space of
the client application. It cannot be run as a separate process. The
communication between client (application) and server (code component) will be
faster as both of them (client & server) reside in the same address
space. And more importantly there is no context switch (switching from one process to another). An example for in-process
server is ActiveX Data Objects library.
Out-of-process Server
An ActiveX code component that is
implemented as .EXE is an out-of-process server. It runs in its own address space. When a
client invokes a method of the server, control switches from client process to
server process (context switch occurs).
An out-of-process application can also be run as a standalone
application.
Creating an ActiveX .DLL
An ActiveX DLL is a collection of object
that can be used by client applications.
Let us create a simple ActiveX code component that is implemented as
in-process server (ActiveX .DLL).
We will create an ActiveX DLL with just one
class. It is important to understand how
to create a class when you are creating an ActiveX DLL, as ActiveX DLL is a
collection of classes. A client application that is using this ActiveX DLL
creates objects of the classes exposed by server and invokes methods and
properties to get the job done.
Time Class
The ActiveX server that we are going to
create contains only one class – Time class. The following is the list of
properties, methods, and events of the class.
Type
|
Name
|
Meaning
|
Property
|
Hour
|
Sets/ returns
the number of hours
|
|
Min
|
Sets/ returns
the number of minutes.
|
|
Second
|
Sets/returns
the number of minutes.
|
Method
|
IncrementSecond
|
Increments the
time by one second.
|
|
SetToCurrent
|
Sets the time
to current system time.
|
|
GetTime
|
Returns time
of the class in HH: MM: SS format.
|
|
SetTime
|
Takes time in
HH: MM: SS format and changes time of the class to the given time.
|
Event
|
InvalidTime
|
Raised whenever
Hour, Min, or Second property is set to an invalid value.
|
Table
25.1: Members of Time class.
The following are the major steps in
creating an ActiveX DLL
¨
Create a project of ActiveX DLL
type
¨
Create as many class modules as
required.
¨
Change properties of project
¨ Create .DLL file
To
creating an ActiveX DLL project:
1.
Select File -> New Project and select ActiveX DLL as the type of the project.
2.
Visual Basic creates a new
project with a single class module with Class1 and change the name to time.
Using Class Builder utility
Class builder utility could be used to
create skeleton for methods, properties and events. Let us use class builder
utility to create attributes of Time
class.
To
invoke Class Builder Utility:
1.
Select Add-In Manager option of Add-Ins
Menu.
2.
In Add-In Manager window double click on VB 6 Class Builder Utility
3.
Then message Loaded appears under Load Behavior column.
4.
Click on Ok.
5.
Select Add-Ins menu and choose Class
Builder Utility to invoke Class Builder.
6.
If Class Builder displays a
warning message, just ignore it and continue.
Renaming Class1 to Time
1.
Select Class1 in Classes Pane of
Class Builder Utility and click on right button.
2. Select Rename option and
rename Class1 to Time.
Creating properties, methods and events using
Class Builder
1.
Click right button on Time
class
2.
Select New-> Property option from popup menu.
3.
Enter the name of the property
as hour and change data type to Integer.
4.
In declaration group leave the Public Property radio button selected.
5.
And click on Ok
At this stage class builder displays a
property in the left pane.
6.
Repeat the process for Min and Second properties.
7.
Click right button on Time
class and select New->Method from
popup menu.
8.
Enter IncrementSecond as the name of the method.
9.
Select Attributes table and
enter “Increment time by one second” as the description. Whatever description
you enter here will be displayed in Object Browser when you select this method.
10.
Click on Ok
11.
Repeat the same process for SetToCurrent method. Enter “Sets time
to current system time” as the description.
12.
Again select New->Method from popup menu and
enter SetTime as the name of the
method and “Changes the time to the given time. Time must be given in HH: MM:
SS format” as description.
13.
Then click on + sign on the
right of Arguments list box and enter the following details
(figure 25.4 ).
Name NewTime
Type String
ByVal Checked
Note: if optional checkbox is
checked then the argument is optional. If no value is passed to the argument
then the given default value will be stored in that.
14.
Create one more method with the
name GetTime and specify the Return Data Type as String.
15.
Select New->Event from popup menu of Time class
16.
Enter InvalidTime as the name of the event and “Fired when an given hour,
min or second is invalid” as the description
Note: You can add property, method and event using icons in toolbar also.
Note: Select tab “All” if you want to see all the attributes of the
class. Otherwise select one of the three tabs (Properties, Methods, and Events)
to display the specific members.
To
update project with changes made in class builder:
1.
Select File-> Update Project
option. Class builder updates the class
module with the details furnished so far.
2.
Exit Class builder with File-> Exit.
If you open Time class module, the code
contains three properties, two methods and one event. The code is shown in
listing 25.1.
'local variable(s) to hold property value(s)
Private mvarMin As Integer 'local copy
Private mvarSecond As Integer 'local copy
Private mvarHour As Integer 'local copy
'To fire this event, use RaiseEvent with the
following syntax:
'RaiseEvent InvalidTime[(arg1, arg2, ... ,
argn)]
Public Event InvalidTime()
Public
Sub SetToCurrent()
End Sub
Public
Sub IncrementSecond()
End Sub
Public
Property Let Hour(ByVal vData As Integer)
'used when assigning a value to the property,
on the left side of an assignment.
'Syntax: X.Hour = 5
mvarHour = vData
End Property
Public
Property Get Hour() As Integer
'used when retrieving value of a property, on
the right side of an assignment.
'Syntax: Debug.Print X.Hour
Hour = mvarHour
End Property
Public
Property Let Second(ByVal vData As Integer)
'used when assigning a value to the property,
on the left side of an assignment.
'Syntax: X.Second = 5
mvarSecond = vData
End Property
Public
Property Get Second() As Integer
'used when retrieving value of a property, on
the right side of an assignment.
'Syntax: Debug.Print X.Second
Second = mvarSecond
End Property
Public
Property Let Min(ByVal vData As Integer)
'used when assigning a value to the property,
on the left side of an assignment.
'Syntax: X.Min = 5
mvarMin = vData
End Property
Public
Property Get Min() As Integer
'used when retrieving value of a property, on
the right side of an assignment.
'Syntax: Debug.Print X.Min
Min
= mvarMin
End Property
Public
Function GetTime() As String
End Function
Public
Sub SetTime(ByVal newtime As String)
End Sub
Listing
25.1: Code written by Class Builder
Modifying the code written by Class Builder
Class Builder utility just creates skeleton
for methods. We have to insert the code to make method operational.
GetTime Method
This method is used to return the time in
HH:MM:SS format. Format function is
used to get leading zero for hour,
minute and second. Format function takes a values and the format using which the value
is to be formatted and returns the formatted values in the form of a string.
For complete details of format function, please see on-line help.
Public
Function GetTime() As String
Dim s
As String
'
Return time in HH:MM:SS format
s
=Format(Hour,"00")& ":" & Format(Min,
"00")& ":" _
& Format(Second,
"00")
GetTime = s
End Function
Listing
25.2: GetTime Function.
SetTime Method
Takes time in HH: MM: SS format, breaks it
into hours, minutes and seconds and places them into member variables. It
checks whether three values are valid. If they are not valid it raises InvalidTime event.
Public
Sub SetTime(ByVal newtime As String)
Dim h As Integer
Dim m As Integer
Dim s As Integer
'
input must be in HH:MM:SS format
' if
values are invalid then raise INVALIDTIME event
h =
CInt(Mid(newtime, 1, 2))
m =
CInt(Mid(newtime, 4, 2))
s =
CInt(Mid(newtime, 7, 2))
If h
>= 0 And h <= 23 And m >= 0 And m <= 59 And s >= 0 And s <=
59 Then
mvarHour = h
mvarMin = m
mvarSecond = s
Else
RaiseEvent InvalidTime
End If
End Sub
Listing
25.3: SetTime method.
IncrementSecond Method
This method is used to increment seconds by
one. If incrementing the second causes second to exceed 59 then second is set
to 0 and minute is incremented by one. And so on.
Public Sub IncrementSecond()
' increment second by one
mvarSecond = mvarSecond + 1
If mvarSecond > 59 Then
mvarSecond = 0
mvarMin = mvarMin + 1
If
mvarMin > 59 Then
mvarMin = 0
mvarHour = mvarHour + 1
If mvarHour > 23 Then
mvarHour = 0
End If
End
If
End If
End Sub
Listing
25.4: IncrementSecond method.
SetToCurrent method
This is used to change time to current system
time. I have used methods of DataTime object and Time function to get current hour,
minute and second.
Public
Sub SetToCurrent()
'
change time to current system time
mvarHour = DateTime.Hour(Time)
mvarMin = DateTime.Minute(Time)
mvarSecond = DateTime.Second(Time)
End Sub
Listing
25.5: SetToCurrent
method.
Property Procedures
The following are the property procedures
required for Hour, Min and Second properties. In all three, if the value is
assigned is not valid the InvalidTime event is raised.
Public
Property Let Hour(ByVal vData As Integer)
If vData >= 0 And vdate <= 23 Then
mvarHour = vData
Else
RaiseEvent InvalidTime
End
If
End Property
Public
Property Get Hour() As Integer
Hour =
mvarHour
End Property
Public
Property Let Second(ByVal vData As Integer)
If
vData >= 0 And vData <= 59 Then
mvarSecond = vData
Else
RaiseEvent InvalidTime
End
If
End Property
Public
Property Get Second() As Integer
Second = mvarSecond
End Property
Public
Property Let Min(ByVal vData As Integer)
If
vData >= 0 And vData <= 59 Then
mvarMin = vData
Else
RaiseEvent InvalidTime
End If
End Property
Public
Property Get Min() As Integer
Min =
mvarMin
End Property
Listing 25.6: Property
procedures.
That is about the coding part of the
class. Out ActiveX server is almost
ready. Generally an ActiveX server contains more than one class. But as we are
primarily interested in understanding the concept through an example, one class
is quite adequate in our sample ActiveX server.
Save class as name Time.Cls and project as TimeProject.VBP.
Changing properties of ActiveX Server
Invoke Project properties to change the
properties of ActiveX server. Here are the steps to change properties.
1.
Select Project -> Project Properties to invoke properties window of the
current project.
2.
Change Project Name to TimeServer
3.
Change Project Description to “Time
Class By P.Srikanth”.
4.
And click on Ok.
Creating
.DLL file
Now the final step. We have to create .DLL file for the project.
This DLL file is used by the client application. At the time of creating .DLL file Visual
Basic registers this ActiveX server in system register.
Note: All ActiveX components must be registered in the system registry.
Otherwise they cannot be used in client application.
To
create .DLL file:
1.
Select File menu and choose Make
TimeProject.dll option.
2.
When you are prompted to
specify the directory and the name of the file, select the directory in to
which you want to place .DLL file and leave the filename to default (TimeProject).
3.
Click on Ok to create .DLL file.
That is the end of creation of ActiveX
in-process server. In the next section,
we will see how to use this server in a client application.
Using ActiveX Server
Let us create a small project to understand
how to use an ActiveX in-process server. The project type is Standard .EXE type and it contains only
one form.
Here
are the steps to create testing project.
1.
Start a new project using File -> New Project and select Standard Exe as the project type.
2.
Invoke Form designer and place two labels and four command buttons as
shown in figure 25.6.
3.
Change the properties of the
controls and form as follows.
Object
|
Property
|
Value
|
Form
|
Caption
|
Time Class
Demo
|
Label1
|
Caption
|
Time
|
Label2
|
Name
|
LblTime
|
|
Caption
|
00:00:00
|
|
Fontsize
|
16
|
|
Autosize
|
True
|
|
Borderstyle
|
1-Fixed
Single
|
Command1
|
Name
|
CmdSetToCurrent
|
|
Caption
|
&Set To
Current Time
|
Command2
|
Name
|
CmdIncrement
|
|
Caption
|
&Increment
Second
|
Command3
|
Name
|
CmdChangeTime
|
|
Caption
|
&Change
Time
|
Command4
|
Name
|
CmdQuit
|
|
Caption
|
&Quit
|
Now we need to use ActiveX server. But to
use an ActiveX server, first we have to have a reference to ActiveX server in
the current project.
Creating a reference to ActiveX server
Unless you create a reference to ActiveX
server (or any ActiveX component), you cannot access ActiveX server. So, the first step in using an ActiveX server
is creating a reference as follows:
1.
Select Project - > References
Visual Basic displays the list of ActiveX
servers that are registered in the system registry (figure 25.7).
2.
Search for “Time Class By P.Srikanth”. Because
whatever we give as project description in ActiveX server project, that will be
displayed in References window.
3.
Once you locate it, check the check
box on the left. Also observe that the complete path of .DLL file is placed at
the bottom of the window (figure 25.7).
4.
After turning on the check box
click on Ok to close References
window.
Save the project as TimeTest.Vbp and form as TimeTest.Frm.
Writing code for Sample project
We have to first declare an object of Time class with WithEvents keyword. Write code for InvalidTime event of the object. And then write code for command
buttons.
General/Declarations
Option Explicit
'declare an object of TIME class
Dim WithEvents t As Time
Private
Sub cmdChange_Click()
Dim ts As String
'
take time using inputbox
ts =
InputBox("Enter time in HH:MM:SS format", "Time")
If ts
<> "" Then
t.SetTime ts
lbltime.Caption = t.GetTime
End
If
End Sub
Private
Sub cmdquit_Click()
Unload Me
End Sub
Private
Sub cmdSetToCurrent_Click()
t.SetToCurrent
lbltime.Caption = t.GetTime
End Sub
Private
Sub CmdIncrement_Click()
t.IncrementSecond
lbltime.Caption = t.GetTime()
End Sub
Private
Sub Form_Load()
Set
t = New Time
t.SetToCurrent
lbltime.Caption = t.GetTime
End Sub
Private
Sub t_InvalidTime()
MsgBox "Invalid Time"
End Sub
Listing
25.7: Code for event in the form.
Test Run
1. Now run the project. As in Form_Load event Time object is set to
system time, you should see the system time as soon as the project starts.
2. After some time again click on Set To Current Time command button.
The time should be updated to the current system time.
3. Click on Change Time command button and enter 10:10:58 as new
type. This will change the time and new
time is displayed.
4. Clicking on Increment Second button should make it 10:10:59. Again
clicking on it should make it 10:11:00.
See figure 25.8.
5. Now again choose Change Time and enter 30:20:02 as the time. As hour
portion is not valid, SetTime method of the Time class fires InvalidTime event.
And you should see “Invalid Time” message in message box.
That’s all that you have to do to test
whether it is working in the way you want. If you found any mistakes in Time
class then open ActiveX server project, make modifications and then recreate
.DLL file.
No comments:
Post a Comment