简体   繁体   中英

Call function in MFC if I click on Button

Ive made a function in MFC.

HBRUSH NeuerEintrag::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    m_ErrorBrush = new CBrush(RGB(255, 130, 130));
    if ((CTLCOLOR_EDIT == nCtlColor) && (IDC_EDIT1 == pWnd->GetDlgCtrlID()))
    {
        pDC->SetBkColor(RGB(255, 130, 130));
        return (HBRUSH)(m_ErrorBrush->GetSafeHandle()); 
    }
    return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}

Whenever I start the program, the funcion gets called. But I only want, that when I click on a Button, the function gets called. This right here is in antoher function but in the same class:

else
{
    MessageBox (_T("Überprüfen Sie ihre Eingaben"));
    // <-- HERE MUST THE FUNCTION BE CALLED
}   

Im new to MFC and I dont really know, how I can solve this. Can someone explain me, where and what I have to do, to solve this?

If you need to colour your edit box conditionally, set up a member variable and check it in your OnCtlColor() , like:

a) in your dialog.h file

BOOL m_bError;

b) in NeuerEintrag::NeuerEintrag

m_bError = FALSE;

c) after your MessageBox: replace // <-- HERE MUST THE FUNCTION BE CALLED by

{   m_bError = TRUE;
    GetDlgItem(IDC_EDIT1)->Invalidate();
}

d) in your OnCtlColor function

HBRUSH NeuerEintrag::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{   m_ErrorBrush = new CBrush(RGB(255, 130, 130));
    if (CTLCOLOR_EDIT == nCtlColor && IDC_EDIT1 == pWnd->GetDlgCtrlID() && m_bError)
    {   pDC->SetBkColor(RGB(255, 130, 130));
        return (HBRUSH)(m_ErrorBrush->GetSafeHandle()); 
    }
    return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}

e) remember to reset m_bError to FALSE and invalidate the edit control if the validation returns ok

OnCtlColor is called whenever a Control Needs to be painted. If you want give a Control a specific behavior like showing the text in a different Color, you can write your own edit class that handles the OnCtlColor by itself.

TN062 Shows this with CYellowEdit. As in a previous answer you can reserve a flag or the the value of the color itself in this class and use it.

There is also a ready to use class at CodeProject

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