You should probably do this by validating the characters as they're entered:
class CEditBox public CEdit
{
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CEditBox, CEdit)
ON_WM_CHAR()
END_MESSAGE_MAP()
void CEditBox::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// quick validation
if (nChar != _T('+') && nChar != _T('-') && !isdigit(nChar))
return;
CString strText;
GetWindowText(strText);
int nStartChar;
int nEndChar;
GetSel(nStartChar, nEndChar);
CString strNewText = strText.Left(nStartChar) +
nChar +
strText.Right(strText.GetLength() - nEndChar);
CString strFirst = strNewText.Left(1);
// is first character valid?
if (strFirst != _T("+") && strFirst != _T("-") && && !isdigit(strFirst[0]))
return;
CString strSecond = strNewText.Mid(1);
// are remaining characters all digits? (ie no more + or -)
for (int i = 0; i < strSecond.GetLength(); ++i)
{
if (!isdigit(strSecond[i]))
return;
}
CEdit::OnChar(nChar, nRepCnt, nFlags);
}