Introduction
Usually when we are working with COM objects/controls in Visual Basic or ASP, we see
method enumeration, like ListView.ColumnHeaders.Add (some arguments)
.
In order to develop such COM components in VC++ using the ATL COM wizard,
which allows the user to enumerate the methods of one COM object inside the method of
another COM object, this article
helps in getting the method enumeration when using a ATL based COM components in
the Visual Basic and ASP Environments.
It is also possible to access them in the VC++. Here are set of steps to be followed in building such Components
Steps in Developing the Component
- Using the ATL COM wizard, create a DLL project called CoolCodeComponent.
- Insert a 'Simple' object called "coolcode", with class name
Ccoolcode
and Interface name
Icoolcode
- Add a Method called
EnumMethod
to the Icoolcode
interface as follows
HRESULT EnumMethod([out,retval] pEnumComponent *Res)
Note : Here the pEnumComponent
is the pointer to the interface whose methods are to be
enumerated. It will be
declared as a typedef
in the .IDL in step 8 in this article.
- Insert another 'Simple' COM Object into the workspace called 'EnumComponent' with class name
CEnumComponent
and Interface
name IEnumComponent
.
- Add two methods to this interface:
HRESULT Add(int x, int y,[out,retval] int *Sum)
Note : this method is used to add two numbers and return their sum
HRESULT Multiply(int x, int y, [out,retval] int *Mul)
Note : this method is used to multiply two numbers and return their product
- Provide the implementation for the above two methods as follows inside the
EnumComponent.cpp
STDMETHODIMP CEnumComponent::Add(int x, int y, int *Sum)
{
*Sum = x + y;
return S_OK;
}
STDMETHODIMP CEnumComponent::Multiply(int x, int y, int *Mul)
{
*Mul = x * y;
return S_OK;
}
- In coolcode.h file make the following changes:
- add the header file of EnumComponent
#include "EnumComponent.h"
- declare a member variable to
CEnumComponent
like
public :
CComPtr<IEnumComponent> pEnumComp;
- In the constructor of coolcode create the EnumComponent
Ccoolcode()
{
pEnumComp.CoCreateInstance(CLSID_EnumComponent);
}
- In the destructor of coolcode, release the interface to
IEnumComponent
~Ccoolcode()
{
if(pEnumComp != NULL)
pEnumComp.Release();
}
- Changes to the .IDL file:
- In coolcode.cpp, add the following code to
EnumMethod
STDMETHODIMP Ccoolcode::EnumMethod(pEnumComponent *Res)
{
*Res = pEnumComp;
return S_OK;
}
Now build the component in Win32 Release MinDependency mode
How to Use
Check the component in Visual Basic:
- Create a reference to
CoolCodeComponent 1.0 Type Library
- Add a command button to the form and write the following code in button click
Private Sub Command1_Click()
Dim a As New COOLCODECOMPONENTLib.coolcode
MsgBox a.EnumMethod.Add(10, 12)
MsgBox a.EnumMethod.Multiply(10, 20)
End Sub
- When you run the application it will display the result of the two method calls in message box.