Thursday, May 19, 2011

SelectObject() example - Win32

SelectObject() is used to set some property to a device context(DC). SelectObject() changes the specified property and returns old property value ( that is replaced with the new one). Following example shows how to set a new Bitmap object to a DC using SelectObject() function. Note that old Bitmap object is returned and stored in hOldBMP variable.

        {
            // PNG Test code here!!!
            //
            PNGLoader      *pPNG = new PNGLoader("test.png");
            HDC                hDC = GetDC(hWnd);
            HDC                hMemDC = CreateCompatibleDC(hDC);
            HBITMAP         hOldBMP, hNewBMP;

            pPNG->read();
           
            // Display Image onto Screen for validation.
            //
            hNewBMP = CreateBitmap(pPNG->getWidth(), pPNG->getHeight(), 1, 32, pPNG->getBuffer());
            hOldBMP = (HBITMAP)SelectObject(hMemDC, hNewBMP);

            BitBlt(hDC, 0, 0, pPNG->getWidth(), pPNG->getHeight(), hMemDC, 0, 0, SRCCOPY);

            SelectObject(hMemDC, hOldBMP);
            DeleteObject(hNewBMP);
            DeleteDC(hMemDC);
            ReleaseDC(hWnd, hDC);
            delete pPNG;          
        }