Hi to all...
In a MFC application,
I need to change the background color of a drop down list - combo box control.

IDC_MYCOMBO is the resource id and
m_myCombo is the name of the control.

I need to change the backcolor programmatically.
Is there a way to achieve that?

Thanks

Dani AI

Generated

Good concise solution from — handling control colors in an OnCtlColor handler is a common and practical approach. A few pragmatic notes to make that solution robust across styles and Windows versions.

Create and keep a persistent brush rather than allocating inside the paint callback; free it when the dialog is destroyed. For example:

BOOL CMYDlg::OnInitDialog()
{
    CDialog::OnInitDialog();
    m_myBrush.CreateSolidBrush(RGB(255,90,90)); // keep this member alive
    return TRUE;
}

void CMYDlg::OnDestroy()
{
    m_myBrush.DeleteObject();
    CDialog::OnDestroy();
}

Do not instantiate a CPaintDC in OnCtlColor — use the provided pDC. Also confirm which CTLCOLOR value is being delivered: an editable combo (CBS_DROPDOWN) will typically trigger the edit-case, the popup list uses the listbox case, and a non-editable drop-down (CBS_DROPDOWNLIST) may involve the static/display part. If the popup items are not picking up the color, handle the listbox case or the static case accordingly.

For reliable, per-item appearance (selection highlight, different item colors, theming differences on newer Windows), prefer owner-drawn mode (CBS_OWNERDRAWFIXED/VARIABLE) and implement DrawItem. Visual styles can override simple brush-based coloring in some cases; owner-draw removes that ambiguity. Finally, verify the control ID (IDC_MYCOMBO) in the handler and keep GDI objects managed to avoid leaks or painting artifacts. These tweaks preserve the behavior shown by while avoiding common pitfalls.

I will answer to myself :)

HBRUSH CMYDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
{
 
 HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
 
 CPaintDC dc(this);
 if(nCtlColor == CTLCOLOR_EDIT && pWnd->GetDlgCtrlID() == IDC_MYCOMBO)  {
  pDC->SetTextColor(RGB(0, 0, 0));
  pDC->SetBkColor(RGB(255, 90, 90));
  hbr = m_myBrush;
 }
 
 return hbr;
}

may be it will help to others someday.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.