简体   繁体   中英

Cannot figure out how to change MFC control background color

I have been searching for days to figure out how to change a control's background color. The most logical solution I found is here:

http://www.codeguru.com/cpp/controls/editctrl/backgroundcolor/article.php/c3929/Changing-the-Background-Color-of-Edit-Controls.htm

I implemented this tutorial as follows:

class Cbackgroundcolor_mfc_testDlg : public CDialogEx
{
public:
    Cbackgroundcolor_mfc_testDlg(CWnd* pParent = NULL);

    enum { IDD = IDD_BACKGROUNDCOLOR_MFC_TEST_DIALOG };

    protected:
    virtual void DoDataExchange(CDataExchange* pDX);


protected:
    HICON m_hIcon;
    CBrush m_redbrush,m_bluebrush; //<---- here
    COLORREF m_redcolor,m_bluecolor,m_textcolor; //<---- here


    virtual BOOL OnInitDialog();
    afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
    afx_msg void OnPaint();
    afx_msg HCURSOR OnQueryDragIcon();
    DECLARE_MESSAGE_MAP()
public:
    CStatic m_staticTODO;

protected:

    //  |   |   |   and here
    //  v   v   v   
    HBRUSH Cbackgroundcolor_mfc_testDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
    {
        HBRUSH hbr; 

        switch (nCtlColor) 
        { 

            case CTLCOLOR_EDIT:
            case CTLCOLOR_MSGBOX:
            switch (pWnd->GetDlgCtrlID())
            {     

                case IDC_STATICTODO:         

                pDC->SetBkColor(m_bluecolor);    


                hbr = (HBRUSH) m_bluebrush;                                                     

                break;   
            }


            default:
            hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
        }

        return hbr;
    }

};

I also added the necessary lines to OnInitDialog().

As far as I can tell, I have implemented the tutorial properly and yet the control background colors are still not changing. Can someone help me figure out what else I need to do to change the background color of a control?

OnCtlColor is a message handler for WM_CTLCOLOR. You need to add this message to the dialog's message map to get the function called. Add this line inside the message map:

    ON_WM_CTLCOLOR()

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