Programatically create icons from bmp, jpg, png, gif files in your native Windows Mobile applications

December 17, 2008

This post show how you can create and load icons (HICON) from bmp, png, jpg, gif files in your Windows  Mobile applications. Sample code here assumes that source files have 32×32 dimensions and generated icons will also be on same dimensions.

Procedure:

1. Load the source image file into memory and get HBITMAP handle. To accomplish this use GetBitmapHandle function below.

HBITMAP GetBitmapFromFile(TCHAR* pFileName)
{
HBITMAP hbm = NULL;
OSVERSIONINFO osverinfo = {0};

// Get OS version
GetVersionEx(&osverinfo);

if (osverinfo.dwMajorVersion < 4)
{
hbm = SHLoadImageFile(pFileName);
if (hbm == NULL)
{
hbm = SHLoadDIBitmap(pFileName); // works only for bmp
}
}
else
{
// Use imaging library
IImagingFactory *pImgFactory = NULL;
IImage *pImage = NULL;

// Initialize COM
CoInitializeEx(NULL, COINIT_MULTITHREADED);

// Create the imaging factory.
if (SUCCEEDED(CoCreateInstance (CLSID_ImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IImagingFactory,
(void **)&pImgFactory)))
{
//// Load the image from the JPG file.
if (SUCCEEDED(pImgFactory->CreateImageFromFile(pFileName, &pImage)))
{
// Draw the image.
RECT rc = { 0, 0, 32, 32};
// Get the Desktop HDC
HDC hDC = GetDC(NULL);

// Create Compatible DC and Bitmap
HDC memDC = CreateCompatibleDC ( hDC );
hbm = CreateCompatibleBitmap ( hDC, 32, 32 );

// Select HBITMAP into memory DC
SelectObject ( memDC, hbm);

// Draw the image on the memDC
pImage->Draw(memDC, &rc, NULL);

// Release desktop DC
ReleaseDC(NULL, hDC);

pImage->Release();
}

pImgFactory->Release();
}
// Ununitialize COM
CoUninitialize();
}

// return the HBITMAP handle
return hbm;
}

2. Fillup ICONINFO strcuture and call CreateIconIndirect() API to retrieve HICON handle.

// Create an icon
ICONINFO iconinfo = {0};
iconinfo.fIcon = TRUE;
iconinfo.hbmMask  = hBitmap;
iconinfo.hbmColor = hBitmap;

HICON hCustomIcon = CreateIconIndirect(&iconinfo);

// Use hCustomIcon any way you want…..

Advertisements