1

The following snippet is from the OnChange() handler of a multiline CEdit control, which has "WantReturn" set.

void DLG::OnChangeEditPrepareTape() 
{
    CString ss;
    std::vector<char> aTape;
    m_prepareTape.GetWindowText(ss);
    m_prepareTape.SetWindowText(ss);
}

If the SetWindowText() is commented out, the user’s text builds up on the right, and all is well. But, with it in, the text insertion point moves to the left edge, and the user’s characters go in to the left of the existing characters..

I want to put some tinkering text between the two calls, and can get what I want by subclassing CEdit. But I’d be interested to know if there is a way of doing it by Get() & Set().

I’m using Visual C++ 6, with Service Pack 5. Eleven years old now, but then “Software does not wear out” as they say:-).

pnuts
  • 58,317
  • 11
  • 87
  • 139
John White
  • 131
  • 1
  • 3
  • 19

2 Answers2

2

The insertion point is reset by SetWindowText() because, from the control's point of view, its whole text content has just been reset (possibly to the empty string), and both the insertion point and the current selection might not be meaningful enough to keep them around.

You can use GetSel() and SetSel() to implement this behavior yourself:

void DLG::OnChangeEditPrepareTape() 
{
    CString ss;
    std::vector<char> aTape;

    int start, end;
    m_prepareTape.GetSel(start, end);
    m_prepareTape.GetWindowText(ss);

    // Tinker with the text...

    m_prepareTape.SetWindowText(ss);
    m_prepareTape.SetSel(start, end);
}
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
1

You can you use GetSel to retrieve the cursor position before you replace the text, and SetSel to place it in the same location afterwards.

void DLG::OnChangeEditPrepareTape() 
{
    CString ss;
    int start, stop;
    std::vector<char> aTape;
    m_prepareTape.GetWindowText(ss);
    m_prepareTape.GetSel(&start, &stop);
    m_prepareTape.SetWindowText(ss);
    m_prepareTape.SetSel(start, stop);
}

If you modify the text before you put it back in the text box, you can increment or decrement start (and end) accordingly.

gnab
  • 9,251
  • 1
  • 21
  • 13