Cursor in CEdit

Lescha used Ask the Experts™
Is it possible to get and set the text cursor (I-beam) position in CEdit control?

Here is my problem: I want to edit the text the user types while he is typing it, and for this I work with the appropriate message and, if an incorrect text has been typed, alter the string the control displays. However, every time I use SetWindowText to alter the string, the text cursor hops to the beginning of the line. Since I make this checking every time the text of the control changes, there is no need for it to move the cursor - the new character either will or will not be displayed.

Is there a solution or a workaround for my problem?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

I think you need to use SetCaretPos to set caret and PosFromChar to calculate caret point.


This doesn't always work. Here is the code I use (m_ed1 is a CString variable associated with the control):

// Find and store the current char number
CEdit *ed = (CEdit *)GetDlgItem(IDC_EDIT1);
POINT p = ed->GetCaretPos();
int chr = ed->CharFromPos(p);
// Change the text in the edit control
m_ed1 = m_ed1.Left(14);
// Set the current char to the number stored earlier
*ed = (CEdit *)GetDlgItem(IDC_EDIT1);
p = ed->PosFromChar(chr);

This works only if the text has not been changed. If it has been changed, PosFromChar returns (-1,-1) and thus SetCaretPos sets the cursor to the beginning of the control.
OK, there is very simple way:

pEdit->SetSel(n, n);

sets caret before symbol number n.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial