2

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??

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Zrn-dev
  • 99
  • 5
  • You would have to ask the author who wrote the code that is doing that. – Remy Lebeau Jun 14 '22 at 03:41
  • @RemyLebeau there's a distant possibility that someone else knows the corner case this pattern is supposed to protect against. That wouldn't be me though. – Mark Ransom Jun 14 '22 at 03:47
  • It would make sense to link to the said article as a reference point. – Andrew Truckle Jun 14 '22 at 04:13
  • 1
    @MarkRansom the only possibility I can think of is to support the use of `CEdit::Undo()` (`EM_UNDO`), since `CWnd::SetWindowText()` (`WM_SETTEXT`) can't be undone, but `CEdit::SetSel()` (`EM_SETSEL`) and `CEdit::Clear()` (`WM_CLEAR`) can be. – Remy Lebeau Jun 14 '22 at 04:19

1 Answers1

4

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.

IInspectable
  • 46,945
  • 8
  • 85
  • 181