11. How do I draw a bitmap in the background of a dialog?
The trick is to override the OnEraseBkgnd handler. Here's
one way of doing it:
CBitmap bitmapBkgnd;
bitmapBkgnd.Attach (LoadBitmap (AfxGetInstanceHandle(),
MAKEINTRESOURCE(m_iBitmapId)));
BOOL CTestbed2Dlg::OnEraseBkgnd(CDC* pDC)
{
CRect rect;
GetClientRect(&rect);
CDC dc;
dc.CreateCompatibleDC(pDC);
CBitmap* pOldBitmap = dc.SelectObject(&bitmapBkgnd);
int iBitmapWidth, iBitmapHeight ;
int ixOrg, iyOrg;
BITMAP bm;
bitmapBkgnd.GetObject(sizeof(BITMAP),&bm);
iBitmapWidth = bm.bmWidth;
iBitmapHeight = bm.bmHeight;
// If our bitmap is smaller than the background and tiling is
// supported, tile it. Otherwise watch the efficiency - don't
// spend time setting up loops you won't need.
if (iBitmapWidth >= rect.Width() &&
iBitmapHeight >= rect.Height() )
{
pDC->BitBlt (rect.left,
rect.top,
rect.Width(),
rect.Height(),
&dc,
0,
0, SRCCOPY);
}
else
{
for (iyOrg = 0; iyOrg < rect.Height(); iyOrg +=
iBitmapHeight)
{
for (ixOrg = 0; ixOrg < rect.Width();
ixOrg += iBitmapWidth)
{
pDC->BitBlt (ixOrg,
iyOrg,
rect.Width(),
rect.Height(),
&dc,
0,
0, SRCCOPY);
}
}
}
dc.SelectObject(pOldBitmap);
return TRUE;
}
If you have static text items and want them to
have the bitmap as their background, see Tip #37.
Note that the WM_ERASEBKGND message won't appear in ClassWizard by default,
because ClassWizard hides it from you. To create the handler, you'll have to
learn how to stop this hiding... which is a useful thing to know anyway. If you
go to the last right-hand tab (Class Info I think) on ClassWizard, at the bottom
of the tab you'll see a "filter" combo which is set to
"Dialog". Change this to "Window" and then go back to the
Message Map tab. You'll now see a lot more messages to choose from.