Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

visual c++ - how to change background color of a static text control (when a button is pushed or in a timer) in mfc?

I know it can be done with OnCtlColor(), but it changes colors when the form is being loaded and the static texts are to be drawn, I want to do it after form is loaded, with a timer maybe, I searched for a solution but I didn't find a clear one, this is what I wrote:

void CTabFive::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    CWnd* pWnd = this->GetDlgItem(IDC_Chromosome1);
    CDC* dc = pWnd->GetDC();
    dc->SetBkColor(RGB(200,0,0));
    pWnd->Invalidate();
    pWnd->UpdateWindow();
    Invalidate();
    UpdateWindow();
    //flag = true;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No timer is needed. Here I have a bool m_coloured member of the class initialized to false, and toggled in the button press. The OnCtlColor will draw in red or in the system colour depending on the value of m_coloured. Works nicely.

HBRUSH Cmfcvs2010Dlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);

    if (nCtlColor == CTLCOLOR_STATIC && pWnd->GetDlgCtrlID() == IDC_LABEL)
    {
        DWORD d = GetSysColor(COLOR_BTNFACE);

        COLORREF normal = RGB(GetRValue(d), GetGValue(d), GetBValue(d));
        COLORREF red = RGB(255, 0, 0);

        pDC->SetBkColor(m_coloured ? red : normal);

    }
    return hbr;
}


void Cmfcvs2010Dlg::OnBnClickedButton1()
{
    m_coloured = !m_coloured;
    Invalidate();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...