限制CEdit 只输入小数的两种方法

两种方法均来自互联网,仅为了收录

方法一:

新建一个类并且继承类CEdit,重写消息WM_CHAR

添加代码:

void CDoubleEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)

{

         // TODO: 在此添加消息处理程序代码和/或调用默认值

         CString strEdit;

         GetWindowText(strEdit);

         int length=strEdit.GetLength();

         int pos=strEdit.Find('.');

         //8是退格,是小数点,具体参考键盘常用ASCII

         if((nChar>=48 && nChar<=57) || nChar==46 || nChar==8)

         {

                   if(nChar==8)

                   {

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

                            return;

                   }

                   if(((length-pos)<=2 && pos!=-1 && nChar!=46) || pos==-1 )

                   {

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

                   }

         }

}

方法二:

添加CEditON_CHANGE事件

代码如下:

void CDlgTestDlg::OnEnChangeEdit2()

{

         // TODO: 如果该控件是RICHEDIT 控件,它将不

         // 发送此通知,除非重写CDialog::OnInitDialog()

         // 函数并调用CRichEditCtrl().SetEventMask()

         // 同时将ENM_CHANGE 标志运算到掩码中。

         // TODO: 在此添加控件通知处理程序代码

         CString csAreaS;

         GetDlgItem( IDC_EDIT2 )->GetWindowText( csAreaS );

         // 只允许输数据

         int nStringLength = csAreaS.GetLength();

         int nDotCount = 0;

         // 点字符不能多于个

         for ( int nIndex = 0; nIndex < nStringLength; nIndex++ )

         {

                   if ( csAreaS[ nIndex ] == '.' )

                   {

                            nDotCount++;

                            if ( nDotCount > 1 )

                            {

                                     CString csTmp;

                                     csTmp = csAreaS.Left( nIndex );

                                     csTmp += csAreaS.Right( csAreaS.GetLength() - nIndex - 1 );

                                     //csRadius = csRadius.Left( nIndex + 1 ) + csRadius.Right( nStringLength - ( nIndex + 1 ) - 1 );

                                     GetDlgItem( IDC_EDIT2 )->SetWindowText( csTmp );

                                     return;

                            }

                   }

         }

         // 不允许输入数字和点以外的字符

         for ( int nIndex = 0; nIndex < nStringLength; nIndex++ )

         {

                   if ( csAreaS[ nIndex ] != '.' && ( csAreaS[ nIndex ] > '9' || csAreaS[ nIndex ] < '0' ) )

                   {

                            csAreaS = csAreaS.Left( nIndex ) + csAreaS.Right( csAreaS.GetLength() - nIndex - 1 );

                            GetDlgItem( IDC_EDIT2)->SetWindowText( csAreaS );

                            return;

                   }

         }

}

转载于:https://www.cnblogs.com/luoshupeng/archive/2011/09/12/2174289.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值