How to create a CEdit to display only float numbers

9 11 2009

Description

 

 

Have you ever face a situation to make an edit box that support only floating point numbers. That means the edit box do not accept more than one . (dot) and characters. How shall we do it? Just a trick! 🙂

HowCanIDoIt1

 

 

First of all we have to a derive a new CEdit class to our project and make a control of that on our window. Then we need to put a handler for WM_CHAR and EN_UPDATE messages for our custom edit class. Within the WM_CAHR message handler we can backup the existing value and within the EN_UPDATE message handler we can check the modified value. If its a valid double value, then only we need to update this with the edit control otherwise we can keep the previous value.

MyCodeSnippet

 

 

MyEdit.h

class CMyEdit : public CEdit
{
   DECLARE_DYNAMIC(CMyEdit)
public:
   CMyEdit();
   virtual ~CMyEdit();
protected:
   DECLARE_MESSAGE_MAP()
   afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
   afx_msg void OnUpdate();
private:
   CString m_strPrevValue;
   int m_nLastSel;
};

MyEdit.cpp

CMyEdit::CMyEdit()
{
   m_nLastSel = 0;
}

CMyEdit::~CMyEdit()
{
}

BEGIN_MESSAGE_MAP(CMyEdit, CEdit)
   ON_WM_CHAR()
   ON_CONTROL_REFLECT(EN_UPDATE, OnUpdate)
END_MESSAGE_MAP()

void CMyEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
   GetWindowText(m_strPrevValue);
   m_nLastSel = GetSel();
   CEdit::OnChar(nChar, nRepCnt, nFlags);
}
void CMyEdit::OnUpdate()
{
   CString str;
   GetWindowText(str);
   errno = 0;
   LPTSTR endPtr;
   double doubleValue = _tcstod(str, &aEndPtr);
   if (*endPtr)
   {
      SetWindowText(m_strPrevValue);
      SetSel(m_nLastSel);
   }
}

MyNote

 

 

If you want to allows only digits to be entered into the edit control just use the style ES_NUMBER.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: