.h文件
#pragma once
// CMyEdit
class CMyEdit : public CEdit
{
DECLARE_DYNAMIC(CMyEdit)
public:
CMyEdit();
virtual ~CMyEdit();
protected:
DECLARE_MESSAGE_MAP()
virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam);
public:
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
};
.cpp文件
// MyEdit.cpp : implementation file
//
#include "stdafx.h"
#include "MyEdit.h"
#include "resource.h"
// CMyEdit
IMPLEMENT_DYNAMIC(CMyEdit, CEdit)
CMyEdit::CMyEdit()
{
}
CMyEdit::~CMyEdit()
{
}
BEGIN_MESSAGE_MAP(CMyEdit, CEdit)
ON_WM_CHAR()
END_MESSAGE_MAP()
// CMyEdit message handlers
LRESULT CMyEdit::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: Add your specialized code here and/or call the base class
return CEdit::DefWindowProc(message, wParam, lParam);
}
void CMyEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
// TODO: Add your message handler code here and/or call default
UINT ch = nChar;
HWND hWnd = ::GetFocus();
int CtrlId = ::GetDlgCtrlID(hWnd);
if (ch == VK_BACK)
{
CEdit::OnChar(nChar, nRepCnt, nFlags);
}
else
{
if ((ch >= '0' && ch <= '9')|| ch == VK_DELETE)
{
CEdit::OnChar(nChar, nRepCnt, nFlags);
}
}
}
实际使用实例:
在使用的类定义中定义:CMyEdit m_editTimes;
在使用的类函数OnInitDialog中对需要做字符输入限制的编辑控件添加如下语句:
m_editTimesSubclassDlgItem(IDC_EDIT1,this);
如果有字符个数输入限制则在DoDataExchange函数中添加如下语句:
DDX_Text(pDX, IDC_EDIT2, m_csEditTimes); //关联一个CString变量到Edit控件
DDV_MaxChars(pDX, m_csEditTimes, 8); //限制输入的字符数量