自繪按鈕的實現過程
阿新 • • 發佈:2019-01-25
- 申明自繪屬性
- 進行VM_MESUREITEM事件響應,說明按鈕的尺寸
- 進行VM_DRAWITEM訊息的重新響應,說明如何繪製按鈕
首先在vc6中新建工程,選擇MFC並且新建dialog工程
輸入工程名,然後將生成的按鈕等刪除,重新新增兩個按鈕。
為按鈕設定屬性
選擇自繪,就是自己向上貼圖
在dlg類的物件上新增WM_DRAWITEM屬性
在生成的OnDrawItem方法中新增如下程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
//新增繪圖函式
void CMy40_mybuttonDlg::OnDrawItem( int nIDCtl,
LPDRAWITEMSTRUCT lpDrawItemStruct)
{
//
TODO: Add your message handler code here and/or call default
CDC
ButtonDC;
CBitmap
bitmapTrans;
BITMAP
bmp;
CDC
mem;
CRect
rc;
//得到用於繪製按鈕的DC
ButtonDC.Attach(lpDrawItemStruct->hDC);
//準備用於向按鈕區域傳輸點陣圖 mem.CreateCompatibleDC(&ButtonDC);
//獲取按鈕所佔的矩形大小
rc=lpDrawItemStruct->rcItem;
//獲取按鈕目前所處的狀態,根據不同的狀態繪製不同的按鈕
UINT state
= lpDrawItemStruct->itemState;
//如果按鈕已經得到焦點,繪製選中狀態下的按鈕
if (state&ODS_FOCUS)
{
bitmapTrans.LoadBitmap(IDB_BITMAP1);
bitmapTrans.GetBitmap(&bmp);
CBitmap
*old=mem.SelectObject(&bitmapTrans); //向按鈕所在位置傳輸點陣圖
//使用StretcnBlt的目的是為了讓點陣圖隨按鈕的大小而改變
ButtonDC.StretchBlt(rc.left,rc.top,rc.right,rc.bottom,&mem,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);
mem.SelectObject(old);
bitmapTrans.DeleteObject();
//設定文字背景為透明
ButtonDC.SetBkMode(TRANSPARENT);
ButtonDC.DrawText( "已選中" ,&rc,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
}
else
{
bitmapTrans.LoadBitmap(IDB_BITMAP2);
CBitmap
*old2 = mem.SelectObject(&bitmapTrans);
bitmapTrans.GetBitmap(&bmp);
CBitmap
*old=mem.SelectObject(&bitmapTrans);
ButtonDC.StretchBlt(rc.left,rc.top,rc.right,rc.bottom,&mem,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);
ButtonDC.SetBkMode(TRANSPARENT);
ButtonDC.DrawText( "未選中" ,&rc,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
mem.SelectObject(old2);
bitmapTrans.DeleteObject();
}
CDialog::OnDrawItem(nIDCtl,
lpDrawItemStruct);
}
|
編譯執行,執行後得到效果如果所示