以下代码出自《杨老师之Blog——COM组件设计与应用(四)》。
地址:http://blog.vckbase.com/teacheryang/archive/2005/07/04/9135.html
一、由CLSID得到ProgID(以Word为例子)
void CGetProgIDFromCLSIDDlg::OnBnClickedButton1()
{
::CoInitialize(NULL);
HRESULT hr;
CLSID clsid = {0x209ff,0,0,{0xc0,0,0,0,0,0,0,0x46}};
LPOLESTR lpwProgID = NULL;
hr = ::ProgIDFromCLSID(clsid, &lpwProgID);
if(SUCCEEDED(hr))
{
::MessageBoxW(NULL, lpwProgID, L"ProgID", MB_OK);
IMalloc *pMalloc = NULL;
hr = ::CoGetMalloc(1, &pMalloc); //取得IMalloc
if(SUCCEEDED(hr))
{
pMalloc->Free(lpwProgID); //释放ProgID内存
pMalloc->Release(); //释放IMalloc
}
}
::CoUninitialize();
}
运行结果:
二、由ProgID得到CLSID(以Excel为例子)
void CGetProgIDFromCLSIDDlg::OnBnClickedButton2()
{
::CoInitialize(NULL); //COM初始化
//如果是MFC程序,可以使用AfxOleInit()替代
HRESULT hr;
USES_CONVERSION; // 只需要调用一次,就可以在函数中进行多次转换
LPCOLESTR lpwProgID = T2COLE(_T("Excel.Application.14"));
CLSID clsid;
hr = ::CLSIDFromProgID(lpwProgID,&clsid);
CString str;
str.Format("%08X-%04X-%04x-%02X%02X-%02X%02X%02X%02X%02X%02X" ,
clsid.Data1,clsid.Data2,clsid.Data3,
clsid.Data4[0],clsid.Data4[1],clsid.Data4[2],
clsid.Data4[3],clsid.Data4[4],clsid.Data4[5],
clsid.Data4[6],clsid.Data4[7]);
if(SUCCEEDED(hr))
{
::MessageBox(NULL, (LPCSTR)str, _T("CLSID"), MB_OK);
}
::CoUninitialize();
}
运行结果: