-1

I'm doing a desktop app using winapi.

It only happens whenever I try to do it with variables, whenever I pass just text, everything works correctly.

I tried switching out SendMessageW for SendMessageA, but the strings are still displayed wrong. When the text is put in, it is displayed correctly only with SendMessageA and not SendMessageW.

case WM_COMMAND:
    switch (LOWORD(wParam))
    {
    case 2: 
        GetWindowTextA(TextBox, &text[0], len);
        wstring tst = L"test";
        
        SendMessage(TextField, EM_SETSEL, 0, -1);
        SendMessageA(TextField, EM_REPLACESEL, 0, (LPARAM)&tst);
        delete[] text;

        SetWindowText(TextBox, L"");

        break;
    }

enter image description here

And here I just put text instead and it works perfectly fine

SendMessageA(TextField, EM_REPLACESEL, 0, (LPARAM)"test");

enter image description here

Jon Salman
  • 51
  • 7

2 Answers2

0

Credit to Richard Critten

SendMessageW(TextField, EM_REPLACESEL, 0, (LPARAM)(tst.c_str())); You are castring and std::wstring to LPARAM not the data it contains.

Jon Salman
  • 51
  • 7
  • I am glad you have got your solution and thanks for your sharing, I would appreciate it if you mark them as answer and this will be beneficial to other community. – Zeus Mar 05 '21 at 08:31
0

There are two problems with your code:

  • you are clearly using an ANSI-based (char) window, not a Unicode-based (wchar_t) window, as evident by SendMesaageA() working when SendMessageW() doesn't. std::wstring is a Unicode string class. Use std::string instead.

  • the Win32 API has no concept of C++ class types. EM_REPLACESEL is expecting an LPARAM whose value is a char* pointer to a null-terminated C-style string, but you are sending a pointer to a std::wstring object instead. Use the std::string::c_str() method to get a char* pointer to the string's null-terminated character data.

Try this:

string tst = "test";
SendMessageA(TextField, EM_REPLACESEL, 0, reinterpret_cast<LPARAM>(tst.c_str()));
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770