无法弄清楚如何更改MFC控件背景颜色

时间:2014-08-01 17:42:16

标签: c++ visual-studio-2010 colors mfc controls

我一直在寻找如何更改控件背景颜色的日子。我找到的最合理的解决方案是:

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

我按如下方式实现了本教程:

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;
    }

};

我还在OnInitDialog()中添加了必要的行。

据我所知,我已正确实施了教程,但控件背景颜色仍未改变。有人可以帮我弄清楚我还需要做些什么来改变控件的背景颜色吗?

1 个答案:

答案 0 :(得分:1)

OnCtlColor是WM_CTLCOLOR的消息处理程序。您需要将此消息添加到对话框的消息映射中以获取调用的函数。在消息映射中添加以下行:

    ON_WM_CTLCOLOR()