MFC实现Edit输入限制(只允许输入数字,小数点)

其实只要继承CEdit类,并对WM_CHAR消息进行处理就可以了。很简单的,只是我们之前不会,哈哈
1) 项目中添加一个类CEditEx, 继承CEdit
2) 将MFC中的控件变量的类别设置为CEditEx,并为对它进行响应
3)调用WM_CHAR消息,编写相应的响应函数。相当代码如下
CEditEx.h

#pragma once

// CEditEx

class CEditEx : public CEdit
{
	DECLARE_DYNAMIC(CEditEx)

public:
	CEditEx();
	virtual ~CEditEx();

protected:
	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
	afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
};

CEditEx.cpp

// EditEx.cpp : 实现文件
//

#include "stdafx.h"
#include "EditEx.h"

// CEditEx

IMPLEMENT_DYNAMIC(CEditEx, CEdit)

CEditEx::CEditEx()
{
}

CEditEx::~CEditEx()
{
}

BEGIN_MESSAGE_MAP(CEditEx, CEdit)
	ON_WM_CHAR()
	ON_WM_KEYUP()
END_MESSAGE_MAP()

// CEditEx 消息处理程序
void CEditEx::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	// TODO:  在此添加消息处理程序代码和/或调用默认值

	// 处理小数点
	if (nChar == '.'){
		CString str;
		GetWindowText(str);

		// 限制第一位为小数
		if (str.GetLength() == 0){
			// 第一位输入小数点
			MessageBox(_T("第一位不可以是小数点"));
			return;
		}
		// 限制只允许有一个小数点
		if (str.Find('.') == -1){
			CEdit::OnChar(nChar, nRepCnt, nFlags);
		}else{
			CString str;
			GetWindowText(str);
			if (str[0] == '.') {
				SetWindowText(str.Mid(1, str.GetLength()));
				MessageBox(_T("第一位不可以是小数点"));
			}
			// 小数点出现第二次
			MessageBox(_T("小数点只能输入一次"));
		}
	}
	// 数理数字和退格键
	else if ((nChar >= '0' && nChar <= '9') || nChar == 0x08)
	{
		CEdit::OnChar(nChar, nRepCnt, nFlags);
	}else{
		// 出现非数字键,退格键
		MessageBox(_T("只能输入数字,退格键"));
	}
}

// 修复先输入数字之后,可以在第一位输入小数点
void CEditEx::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	if (nChar == VK_DECIMAL || nChar == VK_OEM_PERIOD) {
		CString str;
		GetWindowText(str);
		if (str[0] == '.') {
			SetWindowText(str.Mid(1, str.GetLength()));
			MessageBox(_T("第一位不可以是小数点"));
		}
	}
	CEdit::OnKeyUp(nChar, nRepCnt, nFlags);
	
}

配套资源

  • 4
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值