if ( FAILED(hr) )
{
MessageBox(NULL, "CoRegisterClassObject()", "", MB_OK);
CoUninitialize();
exit(1);
}
// 进入消息循环,直到WM_QUIT到达
MSG ms;
while(GetMessage(&ms, 0, 0, 0))
{
TranslateMessage(&ms);
DispatchMessage(&ms);
}
// 注销工厂类
CoRevokeClassObject(regID);
}
// 退出COM环境
CoUninitialize();
MessageBox(NULL, "Server is dying",
"EXE Message!", MB_OK | MB_SETFOREGROUND);
return 0;
}
(七)建立注册文件
注册文件用于添加程序注册表信息,文件内容如下:
REGEDIT
HKEY_CLASSES_ROOT/Justin.TimeBeijingServer.TimeBeijingClass/CLSID = {57E9BE40-AE4F-493b-A79B-FBBF7EC7F2AE}
HKEY_CLASSES_ROOT/CLSID/{57E9BE40-AE4F-493b-A79B-FBBF7EC7F2AE} = Justin.TimeBeijingServer.TimeBeijingClass
HKEY_CLASSES_ROOT/CLSID/{57E9BE40-AE4F-493b-A79B-FBBF7EC7F2AE}/LocalServer32 = D:/COM/Debug/COM.exe
双击此文件,将注册信息加入注册表。
(八)建立客户端
上面的程序编译链接后就可以得到一个本地EXE COM服务器。下面为了测试,我们将建立一个客户程序。
// TEST.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "TEST.h"
#include "../TimeBeijing.h"
#include "../TimeBeijing_i.c"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
cout << "初始化COM环境" << endl;
CoInitialize(NULL);
HRESULT hr;
IClassFactory* pICF = NULL;//定义接口指针
ITimeBeijing *pTimeBeijing = NULL;
cout << "获取工厂接口指针" << endl;
hr = CoGetClassObject(CLSID_TimeBeijingClass,
CLSCTX_LOCAL_SERVER,
NULL,
IID_IClassFactory,
(void**)&pICF);
if ( FAILED(hr) )
{
MessageBox(NULL, "CoGetClassObject()", "fail", MB_OK);
exit(1);
}
cout << "获取ITimeBeijing接口指针" << endl;
hr = pICF->CreateInstance(NULL,
IID_ITimeBeijing,
(void**)&pTimeBeijing);
if ( FAILED(hr) )
{
MessageBox(NULL, "CoCreateInstance()", "fail", MB_OK);
exit(1);
}
int h, m, s;
pTimeBeijing->GetTimeBeijing(&h, &m, &s);//使用接口
printf("Time NOW : %d : %d : %d/n", h, m, s);//显示结果
if ( pICF ) pICF->Release();//释放接口
if ( pTimeBeijing ) pTimeBeijing->Release();
cout << "退出COM环境" << endl;
CoUninitialize();
cout << "END" << endl;
getchar();
return 0;
}
(九)测试结果
初始化COM环境
获取工厂接口指针
获取ITimeBeijing接口指针
Time NOW : 12 : 54 : 23
退出COM环境
END