![]() ![]() |
|
限制文本编辑框输入的中英文字符字数 | |
作者:佚名 文章来源:不详 点击数 更新时间:2008/11/1 20:41:11 文章录入:杜斌 责任编辑:杜斌 | |
|
|
class CLimitLengthEdit : public CWindowImpl<CLimitLengthEdit , CEdit> { public: CLimitLengthEdit() {}; virtual ~CLimitLengthEdit(){}; BOOL SubclassWindow(HWND hWnd) {typedef CWindowImpl<CLimitLengthEdit , CEdit> CWindowBase;return CWindowBase::SubclassWindow(hWnd);}; protected: BEGIN_MSG_MAP(CLimitLengthEdit) END_MSG_MAP() }; 在CXXXDlg.h中CXXXDlg类的定义处加入消息映射以及响应函数声明 protected: BEGIN_MSG_MAP(CRequestDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_HANDLER(IDC_EDIT_MESSAGE,EN_CHANGE,OnEditChange) //IDC_EDIT_MESSAGE为编辑控件的ID REFLECT_NOTIFICATIONS_EX() END_MSG_MAP() LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnEditChange(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/); 加入成员变量 private: CLimitLengthEdit m_llEdit; 在实现文件CXXXDlg.cpp中加入消息处理函数 #define MAX_LIMIT_LEN 20 //考试大提示:字符长度限制为中文10个,英文20个 LRESULT CRequestDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { m_llEdit.SubclassWindow(GetDlgItem(IDC_EDIT_MESSAGE)); ::SetFocus(GetDlgItem(IDC_EDIT_MESSAGE)); return 0; } LRESULT CRequestDlg::OnEditChange(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CString strText; TCHAR msg[128]; m_llEdit.GetWindowText(msg , 128); strText.Format(_T("%s"),msg); int nPixelPos = 0; int nCount = 0; int pos = 0; int iLen = strText.GetLength(); for(int i = 0; i < iLen;) { if(IsDBCSLeadByte(strText[i])) { nCount ++; i += 2; if(i > 20) { HideCaret(); m_llEdit.SetSel(0,-1); m_llEdit.ReplaceSel(strText.Left(i - 2)); ShowCaret(); m_llEdit.SetLimitText(nCount); break; } else { m_llEdit.SetLimitText(20); } } else { nCount ++; i++; if(i > 20) { HideCaret(); m_llEdit.SetSel(0,-1); m_llEdit.ReplaceSel(strText.Left(i - 1)); ShowCaret(); m_llEdit.SetLimitText(nCount); break; } else { m_llEdit.SetLimitText(20); } } } strText.ReleaseBuffer(); return FALSE; } |
|
![]() ![]() |