I'm having a problem appending std::wstring to my Win32 edit. It compiles without errors, but the displayed text is not what was originally in the std::wstring. Is there a better way to do what I'm doing(below), or should I use the RichEdit(last resort option).

My appendTextToEdit function below is self-explanatory, It appends text to the edit. I think the problem lies in the second SendMessage call, where I cast newText(LPCWSTR) to LPARAM. Please advise

void appendTextToEdit( HWND Edit, LPCWSTR newText ){
    int TextLen = SendMessage(hEdit, WM_GETTEXTLENGTH, 0, 0);
    SendMessage(hEdit, EM_SETSEL, (WPARAM)TextLen, (LPARAM)TextLen);
    SendMessage(hEdit, EM_REPLACESEL, FALSE, (LPARAM) newText);
Deleted Member

Be VERY careful when using WinAPI's wrapper functions..

Many gcc/g++ implementations define SendMessage as SendMessageA if _UNICODE and UNICODE is NOT defined. Otherwise it is defined as SendMessageW.

You need to either define those for your project OR explicitly use the WideCharacter version of the functions as shown below:

//Use with std::string..
void appendTextToEdit(HWND Edit, LPCSTR newText)
    int TextLen = SendMessageA(hEdit, WM_GETTEXTLENGTH, 0, 0);
    SendMessageA(hEdit, EM_SETSEL, (WPARAM)TextLen, (LPARAM)TextLen);
    SendMessageA(hEdit, EM_REPLACESEL, FALSE, (LPARAM)newText);

//Use with std::wstring..
void appendTextToEdit(HWND Edit, LPCWSTR newText)
    int TextLen = SendMessageW(hEdit, WM_GETTEXTLENGTH, 0, 0);
    SendMessageW(hEdit, EM_SETSEL, (WPARAM)TextLen, (LPARAM)TextLen);
    SendMessageW(hEdit, EM_REPLACESEL, FALSE, (LPARAM)newText);

Edited 1 Year Ago by triumphost

I have already defined _Unicode. Thanks, triumphost, It works now

This question has already been answered. Start a new discussion instead.