代码:
typedef BOOL (*load_function)(void* param, IStream* lpStream); BOOL LoadFromIStream(IStream* lpStream, load_function func, void* param) { return (*func)(param, lpStream); } BOOL LoadFromBuffer(const BYTE* lpBuf, DWORD dwSize, load_function func, void* param) { if (NULL == lpBuf || dwSize <= 0) return FALSE; HGLOBAL hGlobal = ::GlobalAlloc(GHND, dwSize); if (NULL == hGlobal) return FALSE; LPVOID lpBuffer = ::GlobalLock(hGlobal); if (NULL == lpBuffer) { ::GlobalFree(hGlobal); return FALSE; } memcpy(lpBuffer, lpBuf, dwSize); ::GlobalUnlock(hGlobal); LPSTREAM lpStream = NULL; HRESULT hr = ::CreateStreamOnHGlobal(hGlobal, TRUE, &lpStream); if (hr != S_OK) { ::GlobalFree(hGlobal); return FALSE; } BOOL bRet = LoadFromIStream(lpStream, func, param); lpStream->Release(); return bRet; } BOOL LoadFromResource(HINSTANCE hInstance, LPCTSTR pszResourceName, LPCTSTR pszResType, load_function func, void* param) { HRSRC hRsrc = ::FindResource(hInstance, pszResourceName, pszResType); if (NULL == hRsrc) return FALSE; DWORD dwSize = ::SizeofResource(hInstance, hRsrc); if (0 == dwSize) return FALSE; HGLOBAL hGlobal = ::LoadResource(hInstance, hRsrc); if (NULL == hGlobal) return FALSE; LPVOID pBuffer = ::LockResource(hGlobal); if (NULL == pBuffer) { ::FreeResource(hGlobal); return FALSE; } HGLOBAL hGlobal2 = ::GlobalAlloc(GHND, dwSize); if (NULL == hGlobal2) { ::FreeResource(hGlobal); return FALSE; } LPVOID pBuffer2 = ::GlobalLock(hGlobal2); if (NULL == pBuffer2) { ::GlobalFree(hGlobal2); ::FreeResource(hGlobal); return FALSE; } memcpy(pBuffer2, pBuffer, dwSize); ::GlobalUnlock(hGlobal2); LPSTREAM pStream = NULL; HRESULT hr = ::CreateStreamOnHGlobal(hGlobal2, TRUE, &pStream); if (hr != S_OK) { ::GlobalFree(hGlobal2); ::FreeResource(hGlobal); return FALSE; } BOOL bRet = LoadFromIStream(pStream, func, param); if (pStream) pStream->Release(); ::FreeResource(hGlobal); return bRet; } BOOL LoadFromResource(HINSTANCE hInstance, UINT nIDResource, LPCTSTR pszResType, load_function func, void* param) { return LoadFromResource(hInstance, MAKEINTRESOURCE(nIDResource), pszResType, func, param); }
使用办法:
typedef BOOL (*load_function)(void* param, IStream* lpStream); BOOL LoadFromResource(HINSTANCE hInstance, UINT nIDResource, LPCTSTR pszResType, load_function func, void* param); class CImageStatic : public CWindowImpl<CImageStatic, CStatic>, public COwnerDraw<CImageStatic> { private: static BOOL __LoadFunc(void* param, IStream* lpStream) { return ((CImageStatic*)param)->_LoadFunc(lpStream); } BOOL _LoadFunc(IStream* lpStream) { HRESULT hr = x_pImage->Load(lpStream); if (hr == S_OK) { return TRUE; } else { return FALSE; } } protected: CImage *x_pImage;
void SetResId(unsigned int res_id) { if (!x_pImage) delete x_pImage; x_pImage = new CImage(); LoadFromResource(::GetModuleHandle(NULL), res_id, MAKEINTRESOURCE(IDR_GIF), &__LoadFunc, this); this->Invalidate(); }