0

I'm writing a dialog using MFC in C++. The dialog has various CEdit fields and a function that validates all fields. If any field is filled with invalid data, this function disables the OK button. However I would like this function to also indicate which field is invalid. Currently, the function looks like this:

bool myDlg::validateAll() {
    bool bReturnVal = true;
    CBrush red_brush;
    COLORREF red = RGB(255, 204, 204);
    red_brush.CreateSolidBrush(red);
    CDC* pDC;

    if (!myCEditIsValid())) {
        bReturnVal = false;
        pDC = GetDlgItem(MY_CEDIT_ID)->GetDC();
        pDC->SetBkColor(red);
    }
    if (!myOtherCEditIsValid()) {
        bReturnVal = false;
        pDC = GetDlgItem(MY_OTHER_CEDIT_ID)->GetDC();
        pDC->SetBkColor(red);
    }
    ...
    More field validations here
    ...
    return bReturnVal;
}

This doesn't display any color change at all. I'm not sure why it doesn't work. I would imagine I need to update the display, but I can't find how to do that.

I have also tried using OnCtlColor after finding this as a solution to many similar problems found with some Googling. This code looked like this:

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

    COLORREF red = RGB(255, 204, 204);

    // TODO:  Change any attributes of the DC here
    if (pWnd -> GetDlgCtrlID() == MY_CEDIT_ID && !myCEditIsValid()) {
        pDC->SetBkColor(red);
    }

    if (pWnd->GetDlgCtrlID() == MY_OTHER_CEDIT_ID && !myOtherCEditIsValid()) {
        pDC->SetBkColor(red);
    }
    ...
    More field validations here
    ...
    //TODO:  Return a different brush if the default is not desired
    return hbr;
}

This one only paints the field with the current focus if it's invalid. None of the other invalid fields are painted.

If anyone could point me to a valid solution that will check all fields and paint them if they are invalid, I would greatly appreciate it.

LLSv2.0
  • 501
  • 6
  • 20

0 Answers0