Implementation process of the Custom button
- Declare the custom property
- Responds to the vm_mesureitem event, indicating the button size.
- Re-responds to the vm_drawitem message, indicating how to draw a button
First, create a project in vc6, select MFC, and create a dialog project.
Enter the project name, delete the generated buttons, and add the two buttons again.
Set attributes for buttons
Select "self-painting", that is, you can map the image up.
Add the wm_drawitem attribute to the DLG class object.
Add the following code to the generated ondrawitem method:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
// Add a plotting function 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;
// Obtain the DC used for drawing the button
ButtonDC.Attach(lpDrawItemStruct->hDC);
// Prepare a bitmap for transmission to the button Area
mem.CreateCompatibleDC(&ButtonDC);
// Obtain the size of the rectangle occupied by the button
rc=lpDrawItemStruct->rcItem;
// Obtain the current status of the button and draw different buttons based on different statuses.
UINT
state = lpDrawItemStruct->itemState; // If the button gets the focus, draw the button in the selected status
if (state&ODS_FOCUS)
{
bitmapTrans.LoadBitmap(IDB_BITMAP1);
bitmapTrans.GetBitmap(&bmp);
CBitmap *old=mem.SelectObject(&bitmapTrans);
// Transmit bitmap to the button location
// The purpose of using stretcnblt is to change the bitmap with the button size.
ButtonDC.StretchBlt(rc.left,rc.top,rc.right,rc.bottom,&mem,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);
mem.SelectObject(old);
bitmapTrans.DeleteObject();
// Set the text background to transparent
ButtonDC.SetBkMode(TRANSPARENT);
ButtonDC.DrawText( "Selected" ,&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( "Not selected" ,&rc,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
mem.SelectObject(old2);
bitmapTrans.DeleteObject();
}
CDialog::OnDrawItem(nIDCtl, lpDrawItemStruct);
} |
Compile and run the program. The result is as follows: