Edit controls does not provide functions to manipulate single characters. You have two options:
1. Get the complete text, modify it, and store it back
Use
GetWindowText()
to retrieve the text, modify it, and put it back using
SetWindowText()
. When using a CString, a single character can be replaced by the
SetAt()
member function:
void CMyEdit::SetChar1(int nPos, TCHAR c)
{
if (nPos >= 0 && nPos < GetWindowTextLength())
{
CString s;
GetWindowText(s);
s.SetAt(nPos, c);
SetWindowText(s.GetString());
}
}
This method is appropiate for controls with small amount of texts and when multiple operations should be performed, e.g. replacing each occurrence of a character in the string:
void CMyEdit::ReplaceChar(TCHAR cOld, TCHAR cNew)
{
CString s;
GetWindowText(s);
if (s.Replace(cOld, cNew))
SetWindowText(s.GetString());
}
2. Use string replacement with edit control
Use
SetSel()
passing the index of the character to be replaced as start and one more as end point followed by a call to
ReplaceSel()
using a string created from the new character:
void CMyEdit::SetChar2(int nPos, TCHAR c)
{
if (nPos >= 0 && nPos < GetWindowTextLength())
{
TCHAR lpszReplace[2] = {c, _T('\0') };
DWORD dwSaveSel = GetSel();
SetSel(nPos, nPos+1, 1);
ReplaceSel(lpszReplace);
SetSel(dwSaveSel, 1);
}
}
[UPDATE]
From the comments it becomes clear that you need a keypad emulation. This can be done implementing a
WM_CHAR
handler for the edit control and some member variables storing the last pressed char code, event time, and number of repeated presses. Inside the handler check if the char code is identical to the last one and the last event was inside the repeat time span. If so, change the char code passed to the default handler by the new one according to the repeated presses and increment the repeat counter (which may wrap back to null when toggling through all codes):
void CMyEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
UINT nNewChar = nChar;
DWORD dwTime = ::GetTickCount();
if (nChar == m_nLastChar && dwTime - m_dwLastTime < TIMEOUT)
{
m_nRepeatCount++;
SetSel(m_nPos, m_nPos+1, 1);
}
else
{
m_nLastChar = nChar;
m_nRepeatCount = 0;
}
m_dwLastTime = dwTime;
CEdit::OnChar(nNewChar, nRepCnt, nFlags);
}