⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cnumedit.cpp

📁 是一个数字编辑器
💻 CPP
字号:

#include "StdAfx.h"
#include <math.h>
#include "CNumEdit.h"
IMPLEMENT_DYNAMIC(CNumEdit, CEdit)
BEGIN_MESSAGE_MAP(CNumEdit, CEdit)
	//{{AFX_MSG_MAP(CNumEdit)
	//}}AFX_MSG_MAP
	ON_WM_CHAR()
END_MESSAGE_MAP()



CNumEdit::CNumEdit ()
{
	m_digits=0;
}

void CNumEdit::SetDigits (int noOfDigitsAfterZero)
{
	m_digits=noOfDigitsAfterZero;
}

int CNumEdit::GetDigits ()
{
	return m_digits;
}

float CNumEdit::GetValue ()
{
	CString txt;
	GetWindowText(txt);
	return (float) atof(txt);
}

void CNumEdit::SetValue (float x)
{
	CString tmp;
	CString fmt;
	fmt.Format("%%0.%df",m_digits);
	tmp.Format (fmt,(x+(0.5/pow( 10, m_digits+1) ) ) );
	SetWindowText (tmp);
}

void CNumEdit::OnChar (UINT nChar, UINT nRepCnt, UINT nFlags)
{
	if(isdigit (nChar) && CheckInput(nChar) )
		CEdit::OnChar(nChar,nRepCnt,nFlags);
	else
	{
		CString txt;
		GetWindowText(txt);
		switch (nChar) 
		{
		case '+' : // set to absolute value
			{
				float x = (float) atof(txt);
				if (x >0)
					break; // only break if we already >0, else do "case -"
			}
		case '-' : // change sign.
			{
				float x = (float) atof(txt);
				x = -x;
				SetValue(x);
				break;
			}
		case '.' :	 
				if ( txt.Find('.') == -1 && CheckInput(nChar))
					CEdit::OnChar(nChar, nRepCnt, nFlags);
				break; 
		case VK_BACK:
			CEdit::OnChar(nChar, nRepCnt, nFlags);
			break;
		}
	}
}

bool CNumEdit::CheckInput (UINT nChar)
{
	// checks no digit or dots before a minus sign
	// and no more than m_digits after '.'

	int pos = CharFromPos(GetCaretPos()); 
	CString txt;
	GetWindowText(txt);
	int len = txt.GetLength();
	//////// no digits or dot before a minus sign
	int sign = txt.Find('-');
	if ( pos <= sign )
		return false;
	//// no dot before m_digit from end of string
	int dot = txt.ReverseFind('.');
	if ( dot == -1 ) {
		// no dot - check position before accepting
		if ( pos >= len -m_digits )
			return true;
		else
			return false;
	}
	/////// limit digits after '.' 
	if ( len - pos < dot) {
		// no insert if 
		// there is more than m_digits digits after zero.
		if ( pos -dot > m_digits )
			return false;
		// the insert will cause the same
		if ( len - dot> m_digits) 
			return false;
	}
	return true;

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -