The Ex22c Example: An MFC COM Client
The Ex22c example is an MFC program that incorporates a true COM version of the client code you saw in Ex22a. This is a generic MFC Application Wizard–generated Single Document Interface (SDI) EXE program with an added #include statement for the MFC COM headers and a call to AfxOleInit, which initializes the DLL. A Spaceship command on an added Test menu is mapped to the view class handler function shown in the following code. The project also contains a copy of the Ex22b component's


void CEx22cView::OnTestSpaceship()
{
CLSID clsid;
LPCLASSFACTORY pClf;
LPUNKNOWN pUnk;
IMotion* pMot;
IVisual* pVis;
HRESULT hr;
if ((hr = ::CLSIDFromProgID(L"Ex22b.Spaceship", &clsid)) != NOERROR) {
TRACE("unable to find Program ID -- error = %x\n", hr);
return;
}
if ((hr = ::CoGetClassObject(clsid, CLSCTX_INPROC_SERVER,
NULL, IID_IClassFactory, (void **) &pClf)) != NOERROR) {
TRACE("unable to find CLSID -- error = %x\n", hr);
return;
}
pClf->CreateInstance(NULL, IID_IUnknown, (void**) &pUnk);
pUnk->QueryInterface(IID_IMotion, (void**) &pMot); // All three
pMot->QueryInterface(IID_IVisual, (void**) &pVis); // pointers
// should work
TRACE("main: pUnk = %p, pMot = %p, pDis = %p\n", pUnk, pMot, pVis);
// Test all the interface virtual functions
pMot->Fly();
int nPos = pMot->GetPosition();
TRACE("nPos = %d\n", nPos);
pVis->Display();
pClf->Release();
pUnk->Release();
pMot->Release();
pVis->Release();
AfxMessageBox("Test succeeded. See Debug window for output.");
}
To test the client and the component, you must first run the component to update the Registry. Several utilities will help you do this, but you might want to try the RegComp program in the \vcppnet\REGCOMP project on the companion CD. This program prompts you to select a DLL or an OCX file, and then it calls the exported DllRegisterServer function.Both client and component show their progress through TRACE calls. To view the trace result, you need the debugger or some other utilities. You can run either the client or the component from the Visual Studio .NET debugger. If you try to run the component, you'll be prompted for the client pathname. In either case, you don't have to copy the DLL because Windows will find it through the Registry.