MFC2010. 3. 24. 19:59

이전 포스트에서 다이얼로그 베이스에서 각종 컨트롤의 색상을 변경해 봤습니다.
그런데 버튼은 같은 방법으로 색상 변경을 할 수 없습니다.
버튼의 색상 변경하는 방법입니다.

1. 우선 버튼의 속성으로 가서 Owner Draw에 체크합니다.

2. 컨트롤 W를 눌러 클래스 위저드를 실행시킵니다.

3. Message Maps 탭에 다이얼로그의 ID를 선택한 후 Message에서 WM_DRAWITEM을 더블클릭해 메세지맵을 추가합니다.

4. 아래와 같이 코딩합니다.
void CMyDlg::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{   
  if(nIDCtl==IDC_BTN_EXIT)
  {
    CDC dc;
    RECT rect;
    dc.Attach(lpDrawItemStruct ->hDC);   // Get the Button DC to CDC
   
    rect = lpDrawItemStruct->rcItem;     //Store the Button rect to our local rect.
    dc.Draw3dRect(&rect,RGB(255,255,255),RGB(0,0,0));
    dc.FillSolidRect(&rect,RGB(100,100,255));//Here you can define the required color to appear on the Button.
        
    UINT state=lpDrawItemStruct->itemState;  //This defines the state of the Push button either pressed or not.
    if((state & ODS_SELECTED))
        dc.DrawEdge(&rect,EDGE_SUNKEN,BF_RECT);
    else
        dc.DrawEdge(&rect,EDGE_RAISED,BF_RECT);
   
    dc.SetBkColor(RGB(100,100,255));   //Setting the Text Background color
    dc.SetTextColor(RGB(255,0,0));     //Setting the Text Color
   
    TCHAR buffer[MAX_PATH];           //To store the Caption of the button.
    ZeroMemory(buffer,MAX_PATH );     //Intializing the buffer to zero
           ::GetWindowText(lpDrawItemStruct->hwndItem,buffer,MAX_PATH); //Get the Caption of Button Window
        
    dc.DrawText(buffer,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE);//Redraw the  Caption of Button Window
    dc.Detach();  // Detach the Button DC
  }

        CDialog::OnDrawItem(nIDCtl, lpDrawItemStruct);
}

주석을 보시고 적당히 스타일을 변경하시면 됩니다.

if(nIDCtl==IDC_BTN_EXIT)
만일 위 조건문이 없다면 Onwer Draw 속성을 가진 모든 버튼에 적용됩니다.
Posted by 못생긴나무