开发者

When I send and convert std string with win32 SendMessage I'm getting weird characters

I need to append text to win32 edit control i have working function to do this , but the text that printed in the edit control is gibrish why ? the sample code taken from microsoft example from here

void settext(HWND hDlg,std::string s)
{
    //std::wstring ws;开发者_C百科 
    //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 DlgProc im calling :

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

update

even if i do as suggested here :

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

that pass compilation but still the characters printed are gibrish

and if i do :

LPSTR pst = s.c_str()

it doesn't pass compilation the error:

error C2440: 'initializing' : cannot convert from 'const char *' to 'LPSTR'


My guess is that your app is compiled for Unicode and so the window is interpreting your ANSI C string as a Unicode C string, hence the characters from another language.


The problem is that

LPSTR pst = &s[0];

is not null terminated. You need to use

LPCSTR pst = s.c_str();


There's no guarantee that &s[0] is null terminated so you're probably just seeing whatever random memory is there until a null appears after the end of your string. Probably in some compilers/libraries it works out to be null terminated some/all of the time and thus hasn't surfaced until now.

You'll want to use s.c_str() instead.


You can convert your LPSTR to an LPWSTR with ATL so that the 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 will convert a narrow string to a string compatible with the current compilation settings (Unicode/multi-byte). You could also use A2W which explicitly converts ANSI to WIDE, but A2T will always do the right thing regardless of whether you're compiling in Unicode mode or not.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜