AddRef()
{
METHOD_PROLOGUE(CTimeLogServer,TimeLog)
return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG)
CTimeLogServer::XTimeLog::Release()
{
METHOD_PROLOGUE(CTimeLogServer,TimeLog)
return pThis->ExternalRelease();
}
STDMETHODIMP
CTimeLogServer::XTimeLog::QueryInterface(REFIID riid,void**ppvObj)
{
METHOD_PROLOGUE(CTimeLogServer,TimeLog)
return pThis->ExternalQueryInterface(&riid,ppvObj);
}
说明:虽然CCmdTarget类已经实现了IUnknown接口,但是还必须通过上述代码来将嵌套类的IUnknown映射到CCmdTarget支持的IUnknown接口.METHOD_PROLOGUEH宏的两个参数分别是实现组件对象的类和实现接口的嵌套类.
六.实现ItimeLog接口的方法OutputLog
注意本组件的功能是往日志文件中输入日志.
1. 在组件类中添加一个文件指针:
// Attributes
public:
protected:
FILE* m_logfile;
2. 初始化和退出
首先在CTimeLogServer的构造函数中进行一些初始化:
CTimeLogServer::CTimeLogServer()
{
::AfxOleLockApp();
CTime TimeStamp = CTime::GetCurrentTime();
CString FileName;
FileName.Format(_T("%s.log"),TimeStamp.Format("%Y%m%d"));
m_logfile = fopen(FileName,_T("a"));
if(m_logfile)
{
fprintf(m_logfile,_T("# # # # # # # # # # # # # # # # # \n"));
fprintf(m_logfile,_T("开始于:%s"),(LPCTSTR)TimeStamp.Format("%Y年%m月%d日%H:%M %S"));
fprintf(m_logfile,_T("\n"));
}
}
//然后在析构函数中关闭文件
CTimeLogServer::~CTimeLogServer()
{
::AfxOleUnlockApp();
if(m_logfile)
{
CTime TimeStamp = CTime::GetCurrentTime();
fprintf(m_logfile,_T("\n"));
fprintf(m_logfile,_T("结束于:%s"),(LPCTSTR)TimeStamp.Format("%Y年%m月%d日%H:%M %S"));
fprintf(m_logfile,_T("\n"));
fprintf(m_logfile,_T("# # # # # # # # # # # # # # # # #\n"));
fclose(m_logfile);
}
}
3. 实现接口ITimeLog方法
//实现接口ITimeLog方法
STDMETHODIMP
CTimeLogServer::XTimeLog::OutputLog(BSTR* varLogText)
{
METHOD_PROLOGUE(CTimeLogServer,TimeLog)
if(pThis->m_logfile)
{
CTime TimeStamp = CTime::GetCurrentTime();
CString NowTime = TimeStamp.Format("%Y年%m月%d日%H:%M:%S");
CString LogText((LPCWSTR)*varLogText);
fprintf(pThis->m_logfile,"\n%s\n%s\n%",NowTime,LogText);
return NOERROR;
}
else
{
AfxMessageBox("没有日志文件!");
return S_FALSE;
}
}
七.完善组件服务器
在应用对象CTimeLogServerApp的 实现文件中,处理Instance()和ExitInstance()
BOOL CTimeLogServerApp::InitInstance()
{
::AfxOleLockApp();
// Register all OLE server (factories) as running. This enables the
// OLE libraries to create objects from other applications.
COleObjectFactory::RegisterAll();
return TRUE;
}
int CTimeLogServerApp::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
::AfxOleUnlockApp();
retu