简体   繁体   中英

Changing background color for diasabled check Box in MFC

I am working in an MFC windows application. I am using check boxes in Check List Box control ( CCheckListBox class) . While disabling a check box, its color remains gray. Is there any way to change the background color from gray to another color?

You can use the DrawItem method to control the rendering of the control and its list items. To do that, you'll want to derive your own CCheckListBox class and implement that method. For example, I've changed the second item in the list to red.

在此处输入图片说明

The sample code to do that looks like…

void MyCheckListBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
    UINT index = lpDrawItemStruct->itemID;
    CDC *pDC = CDC::FromHandle (lpDrawItemStruct->hDC);
    if (index == 1)
    {
        CRect rect = lpDrawItemStruct->rcItem;
        pDC->FillSolidRect(&rect, RGB(255, 0, 0));
    }
    CString str;
    GetText(index, str);
    pDC->DrawText(str, &lpDrawItemStruct->rcItem, DT_LEFT | DT_VCENTER);
}

The above sample only changes the item's background color. I've left the rest of the processing and any extra rendering up to you.

@rrirower's implementation will work but his code needs some modifications.

(1) Changing the Back ground color of the disabled check Box

void CMyCheckListBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
  CDC dc;
  dc.Attach(lpDrawItemStruct ->hDC);
  RECT rect = lpDrawItemStruct ->rcItem;
  UINT nId=lpDrawItemStruct->itemID;
  CString strItemText;
  GetText(lpDrawItemStruct ->itemID, strItemText);
  if(nId==1 ||nId==3){
    dc.FillSolidRect(&rect,RGB(255,0,0));
    dc.DrawText(strItemText , &rect, DT_LEFT | DT_VCENTER);
  }
  else{
    CCheckListBox::DrawItem(lpDrawItemStruct); 
  } 
  dc.Detach();
}    

在此处输入图片说明

(2) Changing the Disabled check list box text color
replace dc.FillSolidRect(&rect,RGB(255,0,0)); with dc.SetTextColor(RGB(255,0,0));

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM