locked
How to change background color for MFC? RRS feed

  • Question

  • I'm trying to change the background color for the dialog in my MFC project, but nothing seems to be working. So far I have:

    1) Added "CBrush m_brush" to the header public.

    2) Added "m_brush.CreateSolidBrush(RGB(255, 0, 0))" on init.

    3) Added OnCtlColor in Dlg.cpp.

    HBRUSH CScheduleDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) {
    	HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
    	hbr = m_brush;
    
    	return hbr;
    }

    (As well as "afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)" to the header protected)

    The code runs, but the color is still blank. Is there anything else I can do?


    Wednesday, April 10, 2019 7:34 PM

Answers

  • Do you also have a ‘ON_WM_CTLCOLOR()’ declaration and is your handler called?

    • Marked as answer by Danzellen Wednesday, April 10, 2019 9:44 PM
    Wednesday, April 10, 2019 8:30 PM

All replies

  • Do you also have a ‘ON_WM_CTLCOLOR()’ declaration and is your handler called?

    • Marked as answer by Danzellen Wednesday, April 10, 2019 9:44 PM
    Wednesday, April 10, 2019 8:30 PM
  • That is the right recipe.  What do you mean by "color is still blank"?

    "m_brush" doesn't have to be public, and you don't have to call CDialogEx::OnCtlColor in your function, but neither of those things will affect the result.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Wednesday, April 10, 2019 8:34 PM
  • In addition to the points made by Viorel and Tim Roberts if you only want to change the background of the dialog and leave the controls it contains untouched then the handler should include a test.  One possibility would be -

    HBRUSH CScheduleDlg::OnCtlColor(CDC * pDC, CWnd * pWnd, UINT nCtlColor)
    {
    	return nCtlColor == CTLCOLOR_DLG ? (HBRUSH) m_brush : NULL;
    }
    

    Wednesday, April 10, 2019 9:35 PM