Is there any way to accept only characters in MFC Edit Box. We have to restrict every key input except characters.
Printable View
Is there any way to accept only characters in MFC Edit Box. We have to restrict every key input except characters.
The easiest way is to derive a new class from CEdit, implement WM_CHAR messsage handler in it and don't call the base class (CEdit::OnChar(...)) if the the inserted character is not "alphabetic" (use IsCharAlpha API)
To expand on VictorN's fine reply, if you are using common controls 6.0 or later, you could also use the "balloontip" feature to notify your users about the unacceptable character (modified slightly from working code):
Code:void CMEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
EDITBALLOONTIP bt;
CString m_sReason;
if(!IsCharAlpha(nChar)){
bt.cbStruct=sizeof(EDITBALLOONTIP);
bt.pszTitle=L"Unacceptable Character";
m_sReason.Format(L"The character, '%c', is not allowed here.",nChar);
bt.pszText=m_sReason.GetBuffer();
bt.ttiIcon=TTI_ERROR;
SendMessage(EM_SHOWBALLOONTIP,0,(LPARAM)&bt);
MessageBeep(0xFFFFFFFF);
m_sReason.ReleaseBuffer();
return;
}
CEdit::OnChar(nChar, nRepCnt, nFlags);
}
Hi Victor and Hoxsiew,
Thanks for your reply.
But my doubt is that, I am using MFC AppWizard Dilog Box. There are more than one edit box on that dialog. I want to know how the WM_CHAR will be called for a particular edit box. I am doing some calculation in the EN_CHANGE handler of that edit box of my dialog class.
I derived a class called CMEdit from CEdit and added a message handler WM_CHAR to it. I added the code of AlphaDlg::OnChange() into CMEdit::OnChar(). While executing applied a breakpoint at CMEdit::OnChar(), but the control is not going to CMEdit::OnChar().
Since I am new to VC++ and MFC please let me know if I am doing any mistake.
Thanks,
Jawed.
You shouldn't need the EN_CHANGE in the parent dialog. If you are using the resource editor, right-click the edit control, select "Add Variable" and plug-in your CMEdit class for the "Variable Type" field and the class wizard will do all the work for you. This will ensure that the EDIT control is properly subclassed by your derived class and then the WM_CHAR messages should be routed properly.