怎么样在VC中使用COM接口?

怎么样在VC中使用COM接口?

1.在“stdafx.h”中,在

#include <afxwin.h> // MFC 核心和标准组件
#include <afxext.h> // MFC 扩展
#include <afxdisp.h> // MFC 自动化类

前面加上
#include <afx.h>
#include <wininet.h>
这两个头文件顺序不可颠倒

即:
#include <afx.h>
#include <wininet.h>
#include <afxwin.h> // MFC 核心和标准组件
#include <afxext.h> // MFC 扩展
#include <afxdisp.h> // MFC 自动化类

2.使用 CoInitialize(NULL) 和 CoUninitialize() 初始化和终止 COM 使用环境。

3.在使用了 ATL COM 接口的源文件头部,包含声明该 ATL COM 接口的头文件即可。
IActiveDesktop =》#include <shlobj.h>

一个使用 ATL COM 的例子:
BOOL CSystemSet::SetWallPaper(CString strImaglePath, DWORD dwStyle)
{
CoInitialize(NULL);

BOOL bRet = FALSE;
HRESULT hr = S_FALSE;
IActiveDesktop* pIAD = NULL;

hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER,
IID_IActiveDesktop, (void**) &pIAD );
if (SUCCEEDED(hr))
{
BOOL bActiveDesktop = FALSE;

COMPONENTSOPT co;
co.dwSize= sizeof(co);
if (SUCCEEDED(pIAD->GetDesktopItemOptions(&co, 0)))
{
if (!co.fActiveDesktop || !co.fEnableComponents)
{
co.fActiveDesktop = TRUE;
co.fEnableComponents = TRUE;
if (SUCCEEDED(pIAD->SetDesktopItemOptions(&co, 0)))
bActiveDesktop = TRUE;
}
else
bActiveDesktop = TRUE;
}
if (bActiveDesktop)
{
WCHAR wszWallpaper [MAX_PATH];
ZeroMemory(wszWallpaper, sizeof(wszWallpaper));

#if defined(_UNICODE)
CopyMemory(wszWallpaper, strImaglePath.GetBuffer(0),
min(MAX_PATH * sizeof(TCHAR), (strImaglePath.GetLength() + 1) * sizeof(TCHAR)));
#else
MultiByteToWideChar(CP_ACP, 0, strImaglePath, -1, wszWallpaper, MAX_PATH);
#endif

WALLPAPEROPT wpo;
wpo.dwSize = sizeof(wpo);
wpo.dwStyle = dwStyle;
if (SUCCEEDED(hr = pIAD->SetWallpaper(wszWallpaper, 0)) &&
SUCCEEDED(hr = pIAD->SetWallpaperOptions(&wpo, 0)) &&
SUCCEEDED(hr = pIAD->ApplyChanges(AD_APPLY_ALL)) &&
SUCCEEDED(hr = pIAD->GetWallpaper(wszWallpaper, MAX_PATH, 0)))
{
bRet = TRUE;
}
}
pIAD->Release();
}

CoUninitialize();
return bRet;
}