vc如何实现按钮上显示icon

首先要在dialog设计模板上拖放一个按钮,把它的icon属性设为true,把它的owner draw属性设为true,在资源里导入你要使用的icon

然后要在父窗口的WM_DRAWITEM消息响应函数里添加如下代码:

case WM_DRAWITEM:
  if (wParam == 0)
  {
  }
  else
  {
   LPDRAWITEMSTRUCT lpDIS = (LPDRAWITEMSTRUCT)lParam;
   if (lpDIS->CtlType == ODT_BUTTON && (lpDIS->CtlID == IDC_BUTTON1))
   {
    if (lpDIS->itemState & (ODS_FOCUS | ODS_SELECTED))
    {
     DrawFrameControl(lpDIS->hDC, &lpDIS->rcItem, DFC_BUTTON, DFCS_BUTTONPUSH | DFCS_PUSHED);
     RECT focusRC = lpDIS->rcItem; focusRC.left += 2; focusRC.top += 2; focusRC.right -= 2; focusRC.bottom -= 2;
     //DrawFocusRect(lpDIS->hDC, &focusRC);
     FillRect(lpDIS->hDC, &focusRC, (HBRUSH)GetStockObject(GRAY_BRUSH));
     DrawIconEx(lpDIS->hDC,
      (lpDIS->rcItem.right - lpDIS->rcItem.left - 16)/2,
      (lpDIS->rcItem.bottom - lpDIS->rcItem.top - 16)/2,
      LoadIcon(hInst, (LPCTSTR)IDI_SETTING_ACTIVE),
      16,
      16,
      0,
      NULL,
      DI_NORMAL);
     return TRUE;
    }
    else
    {
     DrawFrameControl(lpDIS->hDC, &lpDIS->rcItem, DFC_BUTTON, DFCS_BUTTONPUSH);
     DrawIconEx(lpDIS->hDC,
      (lpDIS->rcItem.right - lpDIS->rcItem.left - 16)/2,
      (lpDIS->rcItem.bottom - lpDIS->rcItem.top - 16)/2,
      LoadIcon(hInst, (LPCTSTR)IDI_SETTING_NORMAL),
      16,
      16,
      0,
      NULL,
      DI_NORMAL);
     return TRUE;
    }
   }
  }
  break;

按钮上的就是通过DrawIconEx来画上去的,可以准备两幅icon,分别代表按钮别选中时和正常状态。上面是使用16x16尺寸的icon,居中显示,也可以使用其他尺寸,如32x32,128x128等。

你可能感兴趣的:(null,dialog,button)