11.04.2014 Views

Advanced MFC Programming

Advanced MFC Programming

Advanced MFC Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10. Bitmap<br />

……<br />

dwSize=bf.bfSize-sizeof(BITMAPFILEHEADER);<br />

m_hDIB=::GlobalAlloc(GHND, dwSize);<br />

ASSERT(m_hDIB);<br />

lpDIB=(LPSTR)::GlobalLock(m_hDIB);<br />

ASSERT(lpDIB);<br />

Next, the DIB data is read into the global memory:<br />

……<br />

}<br />

}<br />

if(ar.Read(lpDIB, dwSize) != dwSize)<br />

{<br />

::GlobalUnlock(m_hDIB);<br />

::GlobalFree(m_hDIB);<br />

m_hDIB=NULL;<br />

}<br />

else ::GlobalUnlock(m_hDIB);<br />

This completes reading the bitmap file. The DIB data is stored in m_hDIB now.<br />

Creating DDB<br />

On the view side, we need to display the bitmap stored in memory (whose handle is m_hDIB) instead of<br />

the bitmap stored as resource. So we need to modify function CGDIView::OnInitialUpdate(), which will<br />

be called whenever a new file is opened successfully. First, instead of obtaining data from the resource,<br />

function CGDIDoc::GetHDib() is called to get the handle of DIB data:<br />

void CGDIView::OnInitialUpdate()<br />

{<br />

CClientDC dc(this);<br />

CGDIDoc *pDoc;<br />

CBitmap *pBmp;<br />

CPalette *pPalDraw;<br />

LPBITMAPINFO lpBi;<br />

LPLOGPALETTE lpLogPal;<br />

CPalette *pPalOld;<br />

int nSizeCT;<br />

int i;<br />

HBITMAP hBmp;<br />

HGLOBAL hData;<br />

CScrollView::OnInitialUpdate();<br />

pDoc=GetDocument();<br />

ASSERT_VALID(pDoc);<br />

……<br />

hData=pDoc->GetHDib();<br />

Remember in the previous sample, after the DDB and palette are created, we will select them into the<br />

memory DC so that the image can be drawn directly later. In this sample, when a new DIB file is opened,<br />

there may be a bitmap (also a palette) that is being currently selected by the memory DC. If so, we need to<br />

select it out of the memory DC, then lock the global memory and obtain its address that can be used to<br />

access the DIB (In order to create DDB, we need the information contained in the DIB):<br />

……<br />

……<br />

if(hData != NULL)<br />

{<br />

if(m_pPalMemOld != NULL)m_dcMem.SelectPalette(m_pPalMemOld, FALSE);<br />

if(m_pBmpMemOld != NULL)m_dcMem.SelectObject(m_pBmpMemOld);<br />

lpBi=(LPBITMAPINFO)::GlobalLock(hData);<br />

ASSERT(lpBi);<br />

295

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!