从文件中获取HICON资源并保存为ICO图标

本文介绍了如何使用C++通过`ExtractIconEx`函数获取文件图标,并演示了如何使用OleCreatePictureIndirect和IStream实现将HICON保存为ICO文件的过程。主要涉及Windows API和COM技术的应用。
摘要由CSDN通过智能技术生成

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值