MFC 如何让CEdit控件只能输入数字、正负号、小数点(浮点数)

如何让CEdit控件只能输入数字、正负号、小数点(浮点数)
新建类CNumEdit 继承 CEdit

1,在头文件中定义两个变量保存长度和精度
 int m_nLength;
 int m_nDec;

2,在头文件中添加
 //{{AFX_MSG(CNumEdit)
 afx_msg void OnChar( UINT nChar, UINT nRepCnt, UINT nFlags );
 //}}AFX_MSG

3,在cpp文件中添加
BEGIN_MESSAGE_MAP(CNumEdit, CEdit)
 //{{AFX_MSG_MAP(CNumEdit)
 ON_WM_CHAR()
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

4,添加OnChar的实现
void CNumEdit::OnChar( UINT nChar, UINT nRepCnt, UINT nFlags )
{
 //有效按键是数字和负号正号小数点和回退键
 BOOL bConitue = (nChar >= 48 && nChar <= 57) 
     || nChar == 43
     || nChar == 45
     || nChar == 46
     || nChar == 8;
 if(!bConitue)
  return;
 CString sBefore,sAfter;
 GetWindowText(sBefore);
 //保存光标位置
 int nPosCurbgn, nPosCurend;
 GetSel(nPosCurbgn, nPosCurend);
 CEdit::OnChar(  nChar,  nRepCnt,  nFlags);
 GetWindowText(sAfter);
 int nLength = sAfter.GetLength();
 int nPos = sAfter.Find(".");
 //如果长度超过设置长度则返回
 if(nLength > m_nLength)
 {
  SetWindowText(sBefore);
  SetSel(nPosCurbgn,nPosCurend,true);
  return;
 }
 //如果精度超过设置的精度则返回
 if(nPos != CB_ERR && nLength - nPos -1 > m_nDec)
 {
  SetWindowText(sBefore);
  SetSel(nPosCurbgn,nPosCurend,true);
  return;
 }
 //小数点不在首位
 if(nLength > 0 && sAfter.Left(1) == ".")
 {
  SetWindowText(sBefore);
  SetSel(nPosCurbgn,nPosCurend,true);
  return;
 }
 //只有一个小数点
 if(sBefore.Find(".") != CB_ERR && nChar == 46)
 {
  SetWindowText(sBefore);
  SetSel(nPosCurbgn,nPosCurend,true);
  return;
 }
}


5,使用重写的CNumEdit类
在要使用的地方引入CNumEdit的头文件
#include "NumEdit.h"

mfc classwizard->member variables->add variabl..->
输入变量名
category选择control
variable type选择CNumEdit
(
头文件中会添加CNumEdit m_sEdit;
)

在使用类的构造函数里面:
将数字的长度和精度限定为20、2
 m_sEdit.m_nLength = 20;
 m_sEdit.m_nDec = 2;

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值