ccombobox参考:
https://blog.csdn.net/zgqtxwd/article/details/2335759
主要是使用消息ON_WM_CHAR.
头文件:
#pragma once
#include <afxwin.h>
class CMyEdit : public CEdit
{
public:
CMyEdit(void);
~CMyEdit(void);
// 实现
protected:
afx_msg void OnChar(UINT nChar,UINT nRepCnt,UINT nFlags);//声明消息
DECLARE_MESSAGE_MAP()
};
//定制 ccombobox 20180820 这里是为了替换ccombobox中的edit,以限制不能输入非数字
class CMyComobo : public CComboBox
{
public:
CMyComobo(void);
~CMyComobo(void);
CMyEdit m_myEdit;
// 实现
protected:
// afx_msg void OnChar(UINT nChar,UINT nRepCnt,UINT nFlags);//声明消息
DECLARE_MESSAGE_MAP()
public:
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
afx_msg void OnDestroy();
};
实现文件:
#include "stdafx.h"
#include "CMyedit.h"
/
// CMyedit
CMyEdit::CMyEdit()
{
}
// Destruction (virtual)
CMyEdit::~CMyEdit()
{
}
BEGIN_MESSAGE_MAP(CMyEdit, CEdit)
ON_WM_CHAR()
END_MESSAGE_MAP()
void CMyEdit::OnChar(UINT nChar,UINT nRepCnt,UINT nFlags)
{
// TODO: Add your message handler code here and/or call default
// 保证小数点最多只能出现一次
if(nChar=='.')
{
CString str;
// 获取原来编辑框中的字符串
GetWindowText(str);
//若原来的字符串中已经有一个小数点,则不将小数点输入,保证了最多只能输入一个小数点
if(str.Find('.')!=-1)
{
}
// 否则就输入这个小数点
else
{
CEdit::OnChar(nChar, nRepCnt, nFlags);
}
}
// 保证负号只能出现一次,并且只能出现在第一个字符
else if(nChar=='-')
{
CString str;
GetWindowText(str);
// 还没有输入任何字符串
if(str.IsEmpty())
{
CEdit::OnChar(nChar, nRepCnt, nFlags);
}
else
{
int nSource,nDestination;
GetSel(nSource,nDestination);
// 此时选择了全部的内容
if(nSource==0&&nDestination==str.GetLength())
{
CEdit::OnChar(nChar, nRepCnt, nFlags);
}
else
{
}
}
}
// 除了小数点和负号,还允许输入数字,Backspace,Delete
else if((nChar>='0' && nChar<='9')||(nChar==0x08)||(nChar==0x10))
{
CEdit::OnChar(nChar, nRepCnt, nFlags);
}
// 其它的键,都不响应
else
{
}
}
//20180820 定制combobox
BEGIN_MESSAGE_MAP(CMyComobo, CComboBox)
ON_WM_CTLCOLOR()
ON_WM_DESTROY()
END_MESSAGE_MAP()
CMyComobo::CMyComobo(void)
{
}
CMyComobo::~CMyComobo(void)
{
}
HBRUSH CMyComobo::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
if ( nCtlColor == CTLCOLOR_EDIT )
{
if ( m_myEdit.GetSafeHwnd() == NULL )
{
m_myEdit.SubclassWindow( pWnd->GetSafeHwnd() );
}
}
return CComboBox::OnCtlColor( pDC, pWnd, nCtlColor );
}
void CMyComobo::OnDestroy()
{
if ( m_myEdit.GetSafeHwnd() != NULL )
{
m_myEdit.UnsubclassWindow();
}
CComboBox::OnDestroy();
}