2013-03-19 155 views
1

我有一个在中国和印度使用的应用程序。在一组Cedit控件中,我希望用户只能输入属于经典拉丁字母(ISO8859-1很好)的字符。这些控件用于输入注册数据,所以汉字对我们来说是没有用的,因为我们无法阅读它们。限制输入CEdit控件的文本为ISO8859-1字符

该应用程序是基于MFC使用UNICODE构建。
如何限制这些CEdits为拉丁字符。可用的字符是否取决于CEdits中使用的字体或该字体的CharacterSet?
目前,我很困惑,任何帮助,提示,提示,方向将非常感激。

回答

0

这是我在我的程序做的:

void CRequestForm::OnEnChangeEditDetail() 
{ 
    // Filter out the clinical note of any invalid characters as the user types. 
    CString strNotes; 

    m_edit.GetWindowText(strNotes); 
    BOOL bValid = TRUE; 
    int nStartChar, nEndChar; 
    CString strTyped; 
    m_edit.GetSel(nStartChar, nEndChar); 
    if(strNotes.GetLength() - m_strOldNote.GetLength() == 1) 
    { 
    // this is normal user typing 
    CString strInvalidChars; 

    if(nStartChar == nEndChar && nStartChar > 0) 
     strTyped = strNotes.Mid(nStartChar-1, 1); 
    if(!CheckInvalidCharacters(strTyped)) 
    { 
     m_edit.SetWindowText(m_strOldNote); 
     if(nStartChar > 0 && nEndChar > 0) 
     m_edit.SetSel(nStartChar-1, nEndChar-1); 
     else 
     m_edit.SetSel(nStartChar, nEndChar); 
     bValid = FALSE; 
    } 
    } 
    else if(strNotes.GetLength() - m_strOldNote.GetLength() == 2 && 
    nStartChar == nEndChar && nStartChar > 0 && 
    strNotes.Mid(nStartChar-2, 2) == _T("\r\n")) 
    { 
    // Allow CrLf 
    bValid = TRUE; 
    } 
    else 
    { 
    // this is most likely the case of "Pasted" text. need just to remove invalid characters 
    RemoveInvalidChars(strNotes); 
    } 

    if(bValid) 
    { 
    m_strOldNote = strNotes; 
    m_edit.SetWindowText(strNotes); 
    m_edit.SetSel(nStartChar, nEndChar); 
    } 
} 

正如你所看到的,你需要有可变m_strOldNote实例,它是与初始文本(在OnInitDialog)发起。在你的m_edit中你需要处理EN_CHANGE事件。

您将需要两个功能:CheckInvalidCharacters()RemoveInvalidChars()这可能是因为这很容易:

BOOL CRequestForm::CheckInvalidCharacters(const CString& strText) 
{ 
    BOOL bResult = TRUE; 

    int nPos, nLenght; 
    nLenght = strText.GetLength(); 
    for(nPos = 0; nPos < nLenght; ++nPos) 
    { 
    TCHAR ch = strText.GetAt(nPos); 

    if(!(ch >= '0' && ch <= '9') && 
     !(ch >= 'A' && ch <= 'Z') && 
     !(ch >= 'a' && ch <= 'z') && 
     !(ch >= 32 && ch <= 64 && ch != '&') && // Space thru @, excluding |^~\& 
     !(ch == '[' || ch == ']' || ch == '{' || ch == '}' || ch == '_' || ch == '\r' || ch == '\n')) 
    { 
     bResult = FALSE; 
    } 
    } 

    return bResult; 
} 

void CRequestForm::RemoveInvalidChars(CString &str) 
{ 
    // remove non-ASCII characters 
    int nPos, nLenght; 
    nLenght = str.GetLength(); 
    for(nPos = 0; nPos < nLenght; ++nPos) 
    { 
    TCHAR ch = str.GetAt(nPos); 

    if(!((ch >= _T('0') && ch <= _T('9')) || 
     (ch >= _T('A') && ch <= _T('Z')) || 
     (ch >= _T('a') && ch <= _T('z')) || 
     (ch >= 32 && ch <= 64 && ch != _T('&')) || // Space thru @, excluding |^~\& 
      ch == _T('[') || ch == _T(']') || ch == _T('{') || ch == _T('}') || ch == _T('_'))) 
    { 
     str.SetAt(nPos, _T(' ')); 
    } 
    } 
}