COM访问Windows桌面最佳实践案例C++源代码
//#define _WIN32_DCOM //如果出现CoCreateInstance失败,可以尝试打开此项
//#define _WIN32_IE 0x0500 //如果出现方法E_NOIMPL,可以尝试打开此项
#include <atlstr.h>
#include <wininet.h>
#include <shlobj.h>
class CComMgr {
public:
CComMgr() {
(void)::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
}
~CComMgr() {
(void)::CoUninitialize();
}
public:
void test()
{
WCHAR wszWallpaper[MAX_PATH];
CString strPath;
HRESULT hr;
IActiveDesktop* pIAD;
//hr = ::CoInitialize(NULL);
//hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
// 2. 使用外壳提供的活动桌面组件对象类创建COM对象。
// 第四个参数通知COM需要什么接口(这里是IActiveDesktop).
hr = CoCreateInstance(CLSID_ActiveDesktop,
NULL,
CLSCTX_INPROC_SERVER,
IID_IActiveDesktop,
(void**)&pIAD);
if (SUCCEEDED(hr))
{
// 3. 如果COM对象被创建成功,则调用这个对象的GetWallpaper() 方法。
hr = pIAD->GetWallpaper(wszWallpaper, MAX_PATH, 0);
if (SUCCEEDED(hr))
{
// 4. 如果 GetWallpaper() 成功,则输出它返回的文件名字。
// 注意这里使用wcout 来显示Unicode 串wszWallpaper. wcout 是
// Unicode 专用,功能与cout.相同。
std::cout << L"Wallpaper pathis:\n " << CStringA(wszWallpaper) << std::endl;
}
else
{
std::cout << _T("GetWallpaper()failed.") << std::endl;
}
// 5. 释放接口。
pIAD->Release();
}
else
{
std::cout << _T("CoCreateInstance()failed.") << std::endl;
}
//::CoUninitialize();
}
void addItemToDesktop()
{
HRESULT hr;
IActiveDesktop* pActiveDesktop;
COMPONENT compDesktopItem;
//Create an instance of the Active Desktop
hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER,
IID_IActiveDesktop, (void**)&pActiveDesktop);
// Initialize the COMPONENT structure
compDesktopItem.dwSize = sizeof(COMPONENT);
// Insert code that adds the information about the desktop item
// to the COMPONENT structure
wcscpy(compDesktopItem.wszFriendlyName, L"Test");
// Add the desktop item
hr = pActiveDesktop->AddDesktopItem(&compDesktopItem, 0);
// Save the changes to the registry
hr = pActiveDesktop->ApplyChanges(AD_APPLY_ALL);
pActiveDesktop->Release();
}
void enumItemDesktop() {
HRESULT hr;
IActiveDesktop* pActiveDesktop;
COMPONENT compDesktopItem;
int intCount;
int intIndex = 0;
//Create an instance of the Active Desktop
hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER,
IID_IActiveDesktop, (void**)&pActiveDesktop);
hr = pActiveDesktop->GetDesktopItemCount(&intCount, 0);
compDesktopItem.dwSize = sizeof(COMPONENT);
while (intIndex <= (intCount - 1))
{
//get the COMPONENT structure for the current desktop item
hr = pActiveDesktop->GetDesktopItem(intIndex, &compDesktopItem, 0);
//Insert code that processes the structure
std::cout << CStringA(compDesktopItem.wszFriendlyName) << std::endl;
std::cout << CStringA(compDesktopItem.wszSource) << std::endl;
std::cout << CStringA(compDesktopItem.wszSubscribedURL) << std::endl;
//Increment the index
intIndex++;
//Insert code to clean-up structure for next component
}
// Call the Release method
pActiveDesktop->Release();
}
public:
static CComMgr* Inst() {
static CComMgr CComMgrInstance;
return &CComMgrInstance;
}
};