Add a new line using SetWindowText() Function

Ayse picture Ayse · Mar 16, 2013 · Viewed 13.4k times · Source

I have Created an Edit window. I want one string to be displayed in one line and the other string to be displayed on the other line, but the code I am executing only displays the second string. below is my code snippet:

hWndEdit = CreateWindow("EDIT", // We are creating an Edit control
                                NULL,   // Leave the control empty
                                WS_CHILD | WS_VISIBLE | WS_HSCROLL |
                                WS_VSCROLL | ES_LEFT | ES_MULTILINE |
                                ES_AUTOHSCROLL | ES_AUTOVSCROLL,
                                10, 10,1000, 1000,
                                hWnd,
                                0,
                                hInst,NULL);
SetWindowText(hWndEdit, TEXT("\r\nFirst string\r\n"));

SetWindowText(hWndEdit, TEXT("\r\nSecond string"));

OUTPUT: OUTPUT

Answer

Remy Lebeau picture Remy Lebeau · Mar 16, 2013

You are only seeing the last line because SetWindowText() replaces the entire contents of the window in one go.

If you want to display both lines at one time, simply concatenate them together in a single call to SetWindowText():

SetWindowText(hWndEdit, TEXT("\r\nFirst string\r\n\r\nSecond string"));

On the other hand, if you want to insert them at different times, you have to use the EM_SETSEL message to place the edit caret at the end of the window and then use the EM_REPLACESEL message to insert text at the current caret position, as described in this article:

How To Programatically Append Text to an Edit Control

For example:

void AppendText(HWND hEditWnd, LPCTSTR Text)
{
    int idx = GetWindowTextLength(hEditWnd);
    SendMessage(hEditWnd, EM_SETSEL, (WPARAM)idx, (LPARAM)idx);
    SendMessage(hEditWnd, EM_REPLACESEL, 0, (LPARAM)Text);
}

.

AppendText(hWndEdit, TEXT("\r\nFirst string\r\n"));
AppendText(hWndEdit, TEXT("\r\nSecond string"));