简体   繁体   中英

in MFC when CEdit control reached the maximum characters, backspace doesn't work

in my dialog, there is a CEdit box, which set maximum character number. below in DoDataExchange function:

void CDlgSurvey::DoDataExchange(CDataExchange* pDX)
{
    DDX_Control(pDX, IDC_EDIT_SURVEY_ID, m_SurveyIDEdit);//ACUTALLY THE ISSUE IS HERE,SO LATER WE MODIFIED THE CLASS FUNCTION Onchar in m_SurveyIDEdit RELATED
    DDX_Text(pDX, IDC_EDIT_SURVEY_ID, m_SurveyID);
    DDV_MaxChars(pDX, m_SurveyID, SURVEY_ID_FIELD_LENGTH);
}

I found it works. it means I cannot key in characters more than SURVEY_ID_FIELD_LENGTH. But the problem is when I already key in the SURVEY_ID_FIELD_LENGTH length of characters, and I tried to delete some character by using backspace at the end of text. it doesn't work. Did somebody met such problem? and I also try to using another way to set max text in OnInitDialog,

BOOL CDlgSurvey::OnInitDialog()
{
    //set Max Text in Edit Box
    CEdit* pEditControl = (CEdit*)GetDlgItem(IDC_EDIT_SURVEY_ID);
    if (pEditControl)
    {
        pEditControl->SetLimitText(SURVEY_ID_FIELD_LENGTH);
    }

    return TRUE;  // return TRUE unless you set the focus to a control
                  // EXCEPTION: OCX Property Pages should return FALSE
}

the problem is the same, again, I cannot use backspace after it reached the maximum character. Does someone have any idea on how to fix it? thanks,

After checking the code, it is not related to SetLimitText or DDV_MaxChars . The actual issue relates to DDX_Control .

With variable m_SurveyIDEdit we check the character restriction. Once we find the text length has already been reached ( MaxLength ), it just simply returns. That's the problem.

So we have modified the code. We still handle the CEdit::OnChar method. So the key point to handle the issue is: Every time you should examine all unrelated code and see what happens.

My edit control was actually derived from CRestrictedEdit . My solution was to adjust the OnChar handler.

void CRestrictedEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // Get the text of the edit control
    CString sText;
    GetWindowText(sText);

    // if the control limit is already reached, no need to validate the character.
    if ((static_cast<UINT>(sText.GetLength())) == this->GetLimitText())
    {
        CEdit::OnChar(nChar, nRepCnt, nFlags); //THIS IS NEW LINE ADDED
        return;
    }
}

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