The method OnChar controls the input. Depending on the input it acts in different ways.:
- When the input char is a number, a minus or a control code CHertzEdit calls the base class CEdit. This guarantees the usual behaviour of the control for this input
- When the input char is a period, OnChar() checks the presence of another period in the control. When a period already exists, the input is ignored, otherwise accepted (Call of CEdit::OnChar).
- When the input char is a character that can be converted to a unit code, the current unit is truncated and replaced with a new one that is buid from the input.
- All other input is ignored by not calling the base class.
void CHertzEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags){ if (iscntrl(nChar)) { CEdit::OnChar(nChar, nRepCnt, nFlags); return; }
CString str_nChar(nChar); CString strZiel; if (m_bNegativAllowed) strZiel=str_nChar.SpanIncluding("0123456789kKmMhHzZ.-"); else strZiel=str_nChar.SpanIncluding("0123456789kKmMhHzZ.");
// Ist nChar a valid input (s.a.) ? if (strZiel.IsEmpty()) return;
// Ist nChar eine number ? strZiel=str_nChar.SpanIncluding(".kKmMhHzZ"); if (strZiel.IsEmpty()) { // yes // Base class CEdit::OnChar(nChar, nRepCnt, nFlags); return; }
// Get the content of the control int nTextLen=GetWindowTextLength(); char* pChar=new char[nTextLen+1]; // incl. abschliessender \0 GetWindowText(pChar, nTextLen+1); CString strText(pChar);
delete[] pChar;
if (nChar=='.') { // is there a period? if (strText.Find('.')== -1) { // no -> base class CEdit::OnChar(nChar, nRepCnt, nFlags); return; } else { // no -> ignore return; } }
BOOL wasK, wasM, wasHz;
// remove the unit successive if (strText.Remove('m') || strText.Remove('M')) wasM=TRUE; else wasM=FALSE; if (strText.Remove('k') || strText.Remove('K')) wasK=TRUE; else wasK=FALSE; if (strText.Remove('h') || strText.Remove('H')) wasHz=TRUE; else wasHz=FALSE; if ((strText.Remove('z') || strText.Remove('Z')) && wasHz) wasHz=TRUE; else wasHz=FALSE;
strText.Remove(' ');
if (nChar=='k' || nChar=='K') { strText+=" KHz"; SetWindowText(strText); SetModify(); return; } if (nChar=='m' || nChar=='M') { strText+=" MHz"; SetWindowText(strText); SetModify(); return; } if (nChar=='h' || nChar=='H' || nChar=='z' || nChar=='Z') { if (wasK) { strText+=" KHz"; SetWindowText(strText); SetModify(); return; } if (wasM) { strText+=" MHz"; SetWindowText(strText); SetModify(); return; } strText+=" Hz"; SetWindowText(strText); SetModify(); return; } ASSERT(FALSE); // should never happen}