When I send and convert std string with win32 SendMessage, I get strange characters

I need to add text to win32 edit control I have a working function for this, but the text printed in the edit control is gibrish why? sample code taken from microsoft example from here

void settext(HWND hDlg,std::string s) { //std::wstring ws; //ws.assign( s.begin(), s.end() ); //LPWSTR pwst = &ws[0]; //// get temporary LPCWSTR (pretty safe) //LPCWSTR pcwstr = ws.c_str(); //SetDlgItemText(hWndEdit, IDC_EDIT1,pcwstr); HWND hWndEdit = GetDlgItem (hDlg, IDC_EDIT1); LPSTR pst = &s[0]; int ndx = GetWindowTextLength (hWndEdit); SetFocus (hWndEdit); #ifdef WIN32 SendMessage (hWndEdit, EM_SETSEL, (WPARAM)ndx, (LPARAM)ndx); #else SendMessage (hWndEdit, EM_SETSEL, 0, MAKELONG (ndx, ndx)); #endif SendMessage (hWndEdit, EM_REPLACESEL,0,(LPARAM)pst); } 

and from the call to DlgProc im:

 std::string ss("wwwwww"); settext(hwnd,ss); 

Update
even if I do as suggested here:

  SendMessage (hWndEdit, EM_REPLACESEL,0,(LPARAM)s.c_str()); 

which transmit compilation but still typed characters are gibrish
and if I do this:

 LPSTR pst = s.c_str() 

it does not pass error compilation:
error C2440: 'initializing': cannot convert from 'const char *' to 'LPSTR'

+4
source share
4 answers

I assume that your application is compiled for Unicode, and therefore the window interprets your ANSI C string as a Unicode C string, therefore characters from a different language.

+4
source

The problem is

 LPSTR pst = &s[0]; 

does not end with zero. You have to use

 LPCSTR pst = s.c_str(); 
+2
source

There is no guarantee that &s[0] terminated by zero, so you probably just see whatever random memory there is until zero appears after the end of your line. Probably in some compilers / libraries it has been running at zero termination for some time and thus has not yet appeared.

Instead, you want to use s.c_str() .

+1
source

You can convert LPSTR to LPWSTR with ATL so that Unicode APIs can digest it.

 #include <windows.h> #include <atlbase.h> void settext(HWND hDlg,std::string s) { USES_CONVERSION; LPSTR pst = A2T(s.c_str()); 

A2T converts a narrow string to a string compatible with the current compilation settings (Unicode / multi-byte). You can also use A2W, which explicitly converts ANSI to WIDE, but A2T will always do the right thing, whether you compile in Unicode or not.

A2T actually allocates enough stack space for the resulting string, so you don't need to worry about freeing it.

0
source

All Articles