VC讀取EXE檔案的圖示並儲存
在網上搜索儲存EXE檔案圖示的方法,找到許多文章,一大堆程式碼,10幾個函式,一堆結構及定義,看著都頭大。複製下來後,編譯出錯,少這個少那個的,搗鼓了半天時間都沒搞好,終於放棄了。 就儲存個圖片,真有那麼複雜嗎!功夫不負有心人,終於找到了簡單的方法,與大家分享下。
相關的結構還是要的:
/******************************************************************************/
// 結構(圖示相關)
/******************************************************************************/
struct ICONDIRENTRY
{
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
DWORD dwImageOffset;
};
struct ICONDIR
{
WORD idReserved;
WORD idType;
WORD idCount;
//ICONDIRENTRY idEntries;
};
struct GRPICONDIRENTRY
{
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
WORD nID;
};
struct GRPICONDIR
{
WORD idReserved;
WORD idType;
WORD idCount;
GRPICONDIRENTRY idEntries;
};
就一個函式,是根據ICON控制代碼儲存圖示為檔案,引數就不解釋了。
//*****************************************************************************
//儲存ICON圖示
//*****************************************************************************
void SaveIcon(HICON hIcon, LPCTSTR szFilePath)
{
PICTDESC picdesc;
picdesc.cbSizeofstruct = sizeof(PICTDESC);
picdesc.picType = PICTYPE_ICON;
picdesc.icon.hicon = hIcon;
IPicture *pPicture=NULL;
LPSTREAM pStream;
LONG size;
char pathbuf[1024];
CFile iconfile;
OleCreatePictureIndirect(&picdesc, IID_IPicture, TRUE, (VOID**)&pPicture);
CreateStreamOnHGlobal(NULL, TRUE, &pStream);
HRESULT hr=pPicture->SaveAsFile(pStream, TRUE, &size);
strcpy(pathbuf, szFilePath);
iconfile.Open(pathbuf, CFile::modeCreate|CFile::modeWrite);
LARGE_INTEGER li;
li.HighPart=0;
li.LowPart=0;
ULARGE_INTEGER ulnewpos;
pStream->Seek(li, STREAM_SEEK_SET, &ulnewpos);
ULONG uReadCount = 1;
while(uReadCount>0)
{
pStream->Read(pathbuf, sizeof(pathbuf), &uReadCount);
if(uReadCount>0) iconfile.Write(pathbuf, uReadCount);
}
pStream->Release();
iconfile.Close();
}
以上好象沒提到EXE檔案呀,文不對題?非也,因為這個太簡單了,API函式已經有了,不值得專門做個函式。
WINSHELLAPI HICON APIENTRY ExtractIconA(HINSTANCE hInst, LPCSTR lpszExeFileName, UINT nIconIndex);
用法:
HICON hIcon=NULL;
hIcon = ExtractIcon(AfxGetInstanceHandle(), “c:\\test.exe”, 0); //獲取圖示,第二個引數為要獲取第幾個圖示
SaveIcon(hIcon, "c:\\test.ico");
要知道EXE檔案中有幾個圖示:
WINSHELLAPI UINT WINAPI ExtractIconExA(LPCSTR lpszFile, int nIconIndex, HICON FAR *phiconLarge, HICON FAR *phiconSmall, UINT nIcons);
UINT nIconCnt = ExtractIconEx("c:\\test.exe", -1, NULL, NULL, 0);
是不是很簡單呀。