#include <string>
#include <tchar.h>
#include <windows.h>
#include <olectl.h>
#pragma comment(lib, "oleaut32.lib")
using namespace std;
HICON GetFileIcon(string lPath)
{
HICON* phiconLarge, * phiconSmall;
phiconLarge = new HICON();
phiconSmall = new HICON();
int nIcon = ::ExtractIconEx(lPath.c_str(),
0,
phiconLarge,
phiconSmall, 2);
HICON *hiconLarge, *hiconSmal;
hiconLarge = phiconLarge;
hiconSmal = phiconSmall;
return *phiconLarge;
}
HRESULT SaveIcon(HICON hIcon, string path) {
// Create the IPicture intrface
PICTDESC desc = { sizeof(PICTDESC) };
desc.picType = PICTYPE_ICON;
desc.icon.hicon = hIcon;
IPicture* pPicture = 0;
HRESULT hr = OleCreatePictureIndirect(&desc, IID_IPicture, FALSE, (void**)&pPicture);
if (FAILED(hr)) return hr;
IStream* pStream = 0;
CreateStreamOnHGlobal(0, TRUE, &pStream);
LONG cbSize = 0;
hr = pPicture->SaveAsFile(pStream, TRUE, &cbSize);
if (!FAILED(hr)) {
HGLOBAL hBuf = 0;
GetHGlobalFromStream(pStream, &hBuf);
void* buffer = GlobalLock(hBuf);
HANDLE hFile = CreateFile(path.c_str(), GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
if (!hFile) hr = HRESULT_FROM_WIN32(GetLastError());
else {
DWORD written = 0;
WriteFile(hFile, buffer, cbSize, &written, 0);
CloseHandle(hFile);
}
GlobalUnlock(buffer);
}
// Cleanup
pStream->Release();
pPicture->Release();
return hr;
}
int main()
{
string lPath = "D:\\KGMusic\\KuGou.exe";
HICON hicon = GetFileIcon(lPath);
SaveIcon(hicon, "C:\\Users\\qiu\\Desktop\\test.ico");
return 0;
}
从文件中获取HICON资源并保存为ICO图标
于 2022-07-27 15:06:08 首次发布
本文介绍了如何使用C++通过`ExtractIconEx`函数获取文件图标,并演示了如何使用OleCreatePictureIndirect和IStream实现将HICON保存为ICO文件的过程。主要涉及Windows API和COM技术的应用。
摘要由CSDN通过智能技术生成