您的位置:首页 > 其它

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

2013-02-27 14:24 651 查看
如何让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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: