سؤال

I'm trying to block certain types of characters from being inserted into my Edit Control by overwriting OnChar and OnKeydown. I'm trying to block more than one point '.' and anything that is not a number.

First I check if there is already a '.' in the Edit Control that has the focus by setting a variable defined in the dialog class to false:

void MyMainDialog::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
  CWnd * eb1 = GetDlgItem(IDC_EDIT1); //Reference dimension 1 box;
  CWnd * eb2 = GetDlgItem(IDC_EDIT2); //Reference dimension 2 box
  CWnd * eb3 = GetDlgItem(IDC_EDIT3); //Reference dimension 3 box
  CString temp;

  CWnd * focusedHand = MyMainDialog::GetFocus(); //Reference edit box being focused

  if(focusedHand == eb1)
  {
    eb1->GetWindowTextA(temp);
    if(temp.Find('.') != -1)
      checkPoint = true;
    else
      checkPoint = false;
  }
  else if(focusedHand == eb2)
  {
    eb2->GetWindowTextA(temp);
    if(temp.Find('.') != -1)
      checkPoint = true;
    else
      checkPoint = false;
  }
  else if(focusedHand == eb3)
  {
    eb3->GetWindowTextA(temp);
    if(temp.Find('.') != -1)
      checkPoint = true;
    else
      checkPoint = false;
  }

  CDialogEx::OnKeyDown(nChar, nRepCnt, nFlags);
}

At OnChar I'm checking the character being typed. If it is not a number of if it's a point but there was already a point, then I don't call the OnChar from CDialog:

void MyMainDialog::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
   if(nChar == '.' && checkPoint == false) //Is a point and there is no other point
  {
     CDialogEx::OnChar(nChar, nRepCnt, nFlags);   
  }

  if((nChar < '0' || nChar > '9')) //Is not a number
  {
     //Show message to user
  }
  else //Is a number
  {
    CDialogEx::OnChar(nChar, nRepCnt, nFlags);
  }
}

Well, my code is not working. It compiles and it doesn't crash when typing in the edit control, but it simply doesn't do anything. I'm wondering if the right way to overwrite it would be to prevent the call of CDialogEx::OnChar() or if I should make nChar = 0 so that the character displayed will be null. But on top of that the message that I'm trying to display at OnChar is also not displaying, meaning that MyMainDialog::OnChar() is not even being called. Should I overwrite CDialogEx::OnChar() instead?

Thanks for your attention

لا يوجد حل صحيح

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top