此文章为MSWORD.OLB未正确注册导致问题现象及解决方法的代码解决:
代码逻辑:
1、先检测是否注册了wordolb。
检测方法:看能否得到word 文档对象的接口。如果得不到且错误返回码为TYPE_E_CANTLOADLIBRARY,则定义为olb未注册成功。
2、发现未注册,使用regtlibv12.exe注册wordolb。
以下是关键代码:
(1)检测wordolb是否注册
-
/*
-
* check if word ole is register
-
* return 0 MSWORD.OLB is registered
-
* return -1 MSWORD.OLB is not registered
-
* return other CoCreateInstance's return
-
*
-
*/
-
int WordOlbRegisterCheck()
-
{
-
int nReturn = -2;
-
const CLSID CLSID_WORD_DOCUMENT_DOC = {0x00020906, 0x0000, 0x0000,{0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
-
const IID IID_IDocument = {0x0002096b, 0x0000, 0x0000,{0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
-
CoInitialize(NULL);
-
IUnknown *pIDocument = NULL;
-
IUnknown *pUnk = NULL;
-
HRESULT hr = CoCreateInstance(CLSID_WORD_DOCUMENT_DOC, NULL, CLSCTX_LOCAL_SERVER, IID_IUnknown, (void **)&pUnk);
-
if (
-
(hr == S_OK)
-
&& (pUnk != NULL)
-
)
-
{
-
hr = pUnk->QueryInterface(IID_IDocument, (void**)&pIDocument);
-
if (hr == S_OK)
-
{
-
nReturn = 0;
-
pIDocument->Release();
-
}
-
else if (hr == TYPE_E_CANTLOADLIBRARY)
-
{
-
nReturn = -1;
-
}
-
else
-
{
-
nReturn = hr;
-
}
-
pUnk->Release();
-
}
-
else if (hr == TYPE_E_CANTLOADLIBRARY)
-
{
-
nReturn = -1;
-
}
-
else
-
{
-
nReturn = hr;
-
}
-
return nReturn;
-
}
(2)
获得当前程序目录下的注册工具regtlibv12.exe路径
-
//strcat regtool path
-
memset(szPathRegTool, 0, sizeof(TCHAR)*MAX_PATH);
-
DWORD nResult = GetModuleFileName(NULL, szPathRegTool, MAX_PATH);
-
if (nResult > 0 && nResult < MAX_PATH)
-
{
-
while (nResult > 0)
-
{
-
if (szPathRegTool[nResult] != _T('\\'))
-
{
-
szPathRegTool[nResult] = _T('\0');
-
nResult --;
-
}
-
else
-
{
-
break;
-
}
-
}
-
}
-
_tcscat(szPathRegTool, _T("regtlibv12.exe"));
(3)
获得注册表中office安装目录
-
memset(szOfficeDirectory, 0, sizeof(TCHAR)*MAX_PATH);
-
HKEY hKey;
-
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Office\\12.0\\Common\\InstallRoot"), 0, KEY_READ, &hKey) == ERROR_SUCCESS)
-
{
-
DWORD nDataSize = 1024;
-
LPBYTE pData = new BYTE[nDataSize];
-
if (pData != NULL)
-
{
-
memset(pData, 0, nDataSize);
-
DWORD dataType = REG_SZ;
-
if (::RegQueryValueEx(hKey, _T("Path"), NULL, &dataType, pData, &nDataSize) == ERROR_SUCCESS)
-
{
-
memcpy(szOfficeDirectory, pData, nDataSize);
-
}
-
delete pData;
-
pData = NULL;
-
}
-
}
(4)
打开文件对话框选择文件并注册
-
TCHAR szFilters[] = _T("MSWORD.OLB |*.OLB||");
-
CFileDialog fileDlg(TRUE, _T(""), _T("MSWORD.OLB"), OFN_FILEMUSTEXIST|OFN_HIDEREADONLY,
-
szFilters);
-
fileDlg.m_ofn.lpstrInitialDir = szOfficeDirectory;
-
if (fileDlg.DoModal() == IDOK)
-
{
-
//use regtool to register MSWORD.OLB
-
ShellExecute(NULL, _T("open"), szPathRegTool, _T("\"")+fileDlg.GetPathName()+_T("\""), NULL, SW_SHOWNORMAL);
-
}