将输入CEdit控件的文本限制为ISO8859-1字符

时间:2013-03-19 14:16:09

标签: c++ visual-studio-2010 mfc

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

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

1 个答案:

答案 0 :(得分: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);
  }
}

如您所见,您需要拥有一个以初始文本(在OnInitDialog中)启动的实例变量m_strOldNote。在你的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(' '));
    }
  }
}
相关问题