1、新建一個基於對話框的應用程序;
2、以CListBox爲基類派生一個CListBmp類;
3、在對話框添加一個(List Box)列表框控件,爲控件添加一個CListBmp類的成員變量m_list,向工程導入一個位圖資源;
4、在CListBmp添加一個WM_PAINT消息處理函數,在OnPaint()方法繪製列表框控件的背景位圖;
void CListBmp::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
CRect rect;
GetClientRect(&rect); //獲得列表框區域
CBitmap bitmap;
bitmap.LoadBitmap(IDB_BITMAP1);//裝載位圖資源
CDC mendc;
mendc.CreateCompatibleDC(&dc); //創建兼容DC
mendc.SelectObject(&bitmap); //選入位圖對象
dc.BitBlt(0,0,rect.Width(),rect.Height(),&mendc,0,0,SRCCOPY);//繪製背景
//BitBlt是按1:1的比例加載位圖,也可以調用StretchBlt,可以使位圖在拉伸,縮放
//以適應窗口
bitmap.DeleteObject();
ReleaseDC(&mendc);
// Do not call CListBox::OnPaint() for painting messages
}
void CListBmp::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
CRect rect;
GetClientRect(&rect); //獲得列表框區域
CBitmap bitmap;
bitmap.LoadBitmap(IDB_BITMAP1);//裝載位圖資源
BITMAP bmp;
bitmap.GetBitmap(&bmp); //把位圖的寬度高度等信息填充結構體
CDC mendc;
mendc.CreateCompatibleDC(&dc); //創建兼容DC
mendc.SelectObject(&bitmap); //選入位圖對象
//dc.BitBlt(0,0,rect.Width(),rect.Height(),&mendc,0,0,SRCCOPY);//繪製背景
//BitBlt是按1:1的比例加載位圖,也可以調用StretchBlt,可以使位圖在拉伸,縮放
//以適應窗口
dc.StretchBlt(0,0,rect.Width(),rect.Height(),&mendc,
0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);
bitmap.DeleteObject();
ReleaseDC(&mendc);
// Do not call CListBox::OnPaint() for painting messages
}
typedef struct tagBITMAP { /* bm */ int bmType; int bmWidth; int bmHeight; int bmWidthBytes; BYTE bmPlanes; BYTE bmBitsPixel; LPVOID bmBits; } BITMAP;
另外一種實現的方法:
爲什麼在class wizard中找不到對話框的WM_ERASEBKGND消息,是不是對話框沒有這個消息”?其實對話框也是窗口,它也有WM_ERASEBKGND消息,只是MFC的class wizard使用的dialog過濾器將其過濾掉了
在ClassWizard的Classinfo標籤下面Class Name選擇控件所屬的Dlg,在Message filter下面選擇windows
現在就可以爲Dlg添加WM_ERASEBKGND消息
在OnEraseBkgnd裏面添加代碼如下
BOOL CSettingDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
CRect rect;
//GetDlgItem(IDC_LIST1)->GetWindowRect(&rect);
//上面這個和m_list.GetWindowRect(&rect);的執行效果是一樣的
m_list.GetWindowRect(&rect);
ScreenToClient(rect);
CBitmap bitmap;
bitmap.LoadBitmap(IDB_BITMAP1);
BITMAP bmp;
bitmap.GetBitmap(&bmp);
CDC mendc;
mendc.CreateCompatibleDC(pDC);
mendc.SelectObject(&bitmap);
pDC->BitBlt(rect.left,rect.top,rect.Width(),rect.Height(),&mendc,0,0,SRCCOPY);
//pDC->StretchBlt(rect.left,rect.top,rect.Width(),rect.Height(),&mendc,
// 0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);
bitmap.DeleteObject();
ReleaseDC(&mendc);
return TRUE;
//return CDialog::OnEraseBkgnd(pDC);
}