替换桌面快捷方式图标

给桌面快捷方式替换图标
#include <Shobjidl.h> 
#include <shlobj.h>  
bool ChangeLinkIcon(const CString &strLnkName, const CString &strIconPath)
{
	if (strLnkName.IsEmpty() || strIconPath.IsEmpty())
	{
		return false;
	}
	HRESULT hres;
	IShellLink *psl = NULL;
	IPersistFile *pPf = NULL;
	bool bRet = false;

	do//之所以用do while(0)是为了方便流程管理,统一释放
	{
		hres = CoInitialize(NULL);
		if (FAILED(hres))
		{
			break;
		}

		hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
		if (FAILED(hres))
		{
			break;
		}

		hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&pPf);
		if (FAILED(hres))
		{
			break;
		}

		hres = pPf->Load(strLnkName, STGM_READWRITE);
		if (FAILED(hres))
		{
			break;
		}

		hres = psl->SetIconLocation(strIconPath, 0);
		if (FAILED(hres))
		{
			break;
		}

		pPf->Save(strLnkName, TRUE);
		if (FAILED(hres))
		{
			break;
		}

		bRet = true;

	} while (0);

	if (pPf != NULL)
	{
		pPf->Release();
	}
	if (psl != NULL)
	{
		psl->Release();
	}
	CoUninitialize();
	return bRet;
}
使用示例:ChangeLinkIcon(_T("C:\\1.lnk"), _T("C:\\1.ico"));
相关文章
相关标签/搜索