Jan 282010

Simple routine to copy a HBITMAP in memory.  This routine assumes the HBITMAP has been read previously using something like:

HBITMAP hBmp = (HBITMAP)::LoadImage(AfxGetInstanceHandle(), csBitmapFile,
      IMAGE_BITMAP,0,0,LR_LOADFROMFILE);

This routine makes a copy of the bitmap without affecting the original.

// Make a copy of an existing BMP in  memory
void CMyApp::CopyBitmap(HBITMAP hBmp, CBitmap *oBmp)
{
    CBitmap *srcBmp;
    srcBmp = CBitmap::FromHandle(hBmp);

    BITMAP bmpInfo;
    srcBmp->GetBitmap(&bmpInfo);

    CDC srcDC;
    srcDC.CreateCompatibleDC(NULL);

    CBitmap *pOldBmp1 = srcDC.SelectObject(srcBmp);
    oBmp->CreateCompatibleBitmap(&srcDC,bmpInfo.bmWidth,bmpInfo.bmHeight);

    CDC destDC;
    destDC.CreateCompatibleDC(NULL);

    CBitmap *pOldBmp2 = destDC.SelectObject(oBmp);
    destDC.BitBlt(0,0,bmpInfo.bmWidth,bmpInfo.bmHeight,&srcDC,0,0,SRCCOPY);

    srcDC.SelectObject(pOldBmp1);
    destDC.SelectObject(pOldBmp2);
}

Call as:

CBitmap myBmp;

CopyBitmap(hBmp, &myBmp);

Leave a Reply

(required)

(required)