COM应用实例--获取桌面墙纸路径:Win32控制台程序(C++)
/*
功能: 获取桌面墙纸的路径,并建立一个该墙纸的快捷方式保存在指定路径
说明: COM应用实例, Win32控制台程序
*/
#include <iostream>
#include <afx.h>
#include <wininet.h>
#include <Shlobj.h>
using namespace std;
CString getWallpaper() // 获取桌面墙纸的路径
{
WCHAR wszWallpaper[MAX_PATH];
CString strPath;
HRESULT hr;
IActiveDesktop* pIAD;
hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER, IID_IActiveDesktop, (void**)&pIAD);
if(SUCCEEDED(hr))
{
hr = pIAD->GetWallpaper(wszWallpaper, MAX_PATH, 0); // 获得桌面墙纸的路径
if(SUCCEEDED(hr))
{
wcout<<L"Wallpaper path is: "<<wszWallpaper<<endl;
strPath = wszWallpaper;
}
else
cout<<"GetWallpaper() failed."<<endl;
pIAD->Release();
}
else
cout<<"CoCreateInstance() failed."<<endl;
return strPath;
}
bool SavetoShellLink(const CString &path)
{
bool ret = false;
IShellLink *pISL;
IPersistFile *pIPF;
HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pISL);
if(SUCCEEDED(hr))
{
hr = pISL->SetPath(path); // 设置快捷方式的目标
if(SUCCEEDED(hr))
{
hr = pISL->QueryInterface(IID_IPersistFile, (void**)&pIPF);
if(SUCCEEDED(hr))
{
hr = pIPF->Save(L"C:\\wallPaper.lnk", FALSE);
if(SUCCEEDED(hr)) // 快捷方式创建成功
ret = true;
pIPF->Release();
}
}
pISL->Release();
}
return ret;
}
int main()
{
CoInitialize(NULL); // 初始化COM库(让Windows加载DLLs)
CString wallpaper = getWallpaper();
if(wallpaper.GetLength() > 0)
{
if(SavetoShellLink(wallpaper))
cout<<"SavetoShellLink() Succeeded"<<endl;
else
cout<<"SavetoShellLink() Failed"<<endl;
}
CoUninitialize();
return 0;
}