Search code examples
c++visual-c++mfc

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?


Solution

  • 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.

    enter image description here

    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.