Simple Numeric Edit Control | CodeGuru

Simple Numeric Edit Control

–> In our application we needed several edit controls to accept only numbers. One might think to use the Number option on the resource editor, but unfortunately that did not allow us to enter the “-” minus sign. So we needed a different solution. We looked at CodeGuru to find a simple MaskEdit control. There […]

Written By
CodeGuru Staff
CodeGuru Staff
Dec 8, 1998
1 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

–>

In our application we needed several edit controls to accept only numbers.
One might think to use the Number option on the resource editor, but
unfortunately that did not allow us to enter the “-” minus sign. So we
needed a different solution.

We looked at CodeGuru to find a simple MaskEdit control. There were several
to choose from but unfortunately they all did much more that we needed, and
the cursor movement, backspace and delete were not exactly the same as the
standard edit control (which was a requirement). With nothing else to do,
we (like so many others other there) simply wrote our own.

It was unbelievably simple. Here are the steps we took:

1: Created a new class using class wizard where the base class was CEdit.
2: Added this handler for WM_CHAR

void MaskEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
 CString Holder =
  "`~!@#$%^&*()_+|=\\qwertyuiop[]asdfghjkl;'zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:/\"
  "ZXCVBNM<>/";

 if(Holder.Find(nChar)!=-1)
  return;

 CEdit::OnChar(nChar, nRepCnt, nFlags);
}

That’s it. No it does not check for every possibility in the world, but it
does exactly what we needed. It allows us to have an edit control that
works exactly like the default, but only allows numbers and the “-” sign.
There is probably a more elegant way we could have done this, but this was
fast, and it worked.

CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.