c++mfcoverwriteeditboxeditcontrol

why SetSel and clear functions are used in editBox in order to write text


Suppose I have an editBox with text "this is edit",

and then I want to change that text to "second"

I think it is okay to code just like this:

m_edit1.SetWindowTextW(_T("this is edit"));

m_edit1.SetWindowTextW(_T("second"));

but I saw other program that they use like this:

m_edit1.SetWindowTextW(_T("this is edit"));

m_edit1.SetSel(0, -1, TRUE);
m_edit1.Clear();

m_edit1.SetWindowTextW(_T("second"));

My question is:

why they're using SetSel(), Clear() in this case if we can just overwrite it like first code example??


Solution

  • The following code

    m_edit1.SetSel(0, -1, TRUE);
    m_edit1.Clear();
    

    serves no practical purpose, in the context given above. While m_edit1.Clear() sends a WM_CLEAR message to the control that

    can be undone by sending the edit control an EM_UNDO message

    that opportunity is gone once m_edit1.SetWindowTextW(L"second") has run to completion. In summary, there's no difference in observable behavior between executing the first and second snippet of code in the question. They both result in an edit control holding the text "second" with an empty undo queue.

    If indeed the intent was to support undo operations, the code would need to be adjusted to send an EM_REPLACESEL message in place of WM_SETTEXT:

    m_edit1.SetWindowTextW(L"this is edit");
    
    m_edit1.SetSel(0, -1, TRUE);
    m_edit1.ReplaceSel(L"second", TRUE);
    

    This leaves the edit control showing the text "second", but with a non-empty undo queue. Sending an EM_UNDO message to the control will have it show "this is edit" again. Note that an edit control's undo queue has a length of no more than one.