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 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.



Comments

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: August 20, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT When you look at natural user interfaces as a developer, it isn't just fun and games. There are some very serious, real-world usage models of how things can help make the world a better place – things like Intel® RealSense™ technology. Check out this upcoming eSeminar and join the panel of experts, both from inside and outside of Intel, as they discuss how natural user interfaces will likely be getting adopted in a wide variety …

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds