MFC edit control 实现 float, double输入

转载自:https://www.douban.com/note/469018692/?type=like

 

In the early versions of visual studio, the edit control only accept interger if you set the Properties of Number=True, can not accept float and double type.

要想不接受字母char但是接受浮点数, 做法如下:
If we want to accept int, float and double but not char. The method is shown below.

需要重写CEdit类中的OnChar 函数
写一个新的类CMyEdit,继承自CEdit
Firstly, we need to write a new class CMyEdit which is inherted from CEdit and overwrite the OnChar funtion.
 
CMyEdit.h
#pragma once
#include "stdafx.h"
class CMyEdit : public CEdit
{
   DECLARE_DYNAMIC(CMyEdit)
public:
   CMyEdit();
   virtual ~CMyEdit();
protected:
   DECLARE_MESSAGE_MAP()
public:
   afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
};

CMyEdit.cpp
#pragma once
#include "CMyEdit.h"

IMPLEMENT_DYNAMIC(CMyEdit , CEdit)

CMyEdit::CMyEdit()
{
}
CMyEdit::~CMyEdit()
{
}
BEGIN_MESSAGE_MAP(CMyEdit, CEdit)
   ON_WM_CHAR()
END_MESSAGE_MAP()

void CMyEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
        //8: backspace
        //48-57: Number 0-9
        //46: \.
        //45: \-
   if((nChar >=48 && nChar <=57) || (((TCHAR)nChar) == '\.')
        || (((TCHAR)nChar) == '\-') || (nChar == 8))
   //only Numbers, '.', '-' and backspace are allowed
   {
           CEdit::OnChar(nChar, nRepCnt, nFlags);
   }
   else
   {
           MessageBox("Numbers only!", "Tips");
   }
}

Then
add the CMyEdit.h and CMyEdit.cpp into your project
click on the edit control and change Properites : OEM Convert -> true
right click on the edit control->add variable
Category : control
Variable Type: CMyEdit
Variable Name: m_Test(for example)

done

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值