开发者

WINAPI: how to get edit's text to a std::string?

开发者 https://www.devze.com 2023-02-20 23:39 出处:网络
I\'m trying the following code: int length = SendMessage(textBoxPathToSource, WM_GETTEXTLENGTH, 0, 0);

I'm trying the following code:

int length = SendMessage(textBoxPathToSource, WM_GETTEXTLENGTH, 0, 0);
LPCWSTR lpstr;
SendMessage(textBoxPathToSource, WM_GETTEXT, length+1, LPARAM(LPCWSTR));
std::string s(lpstr开发者_开发知识库);

But it doesn't work.


You're using it absolutely incorrectly:

First, you are passing a type instead of a value here:
SendMessage(textBoxPathToSource, WM_GETTEXT, length+1, LPARAM(LPCWSTR));

Interfacing WinAPI functions who write to a string requires a buffer, since std::string's cannot be written to directly. You need to define a space to hold the value:
WCHAR wszBuff[256] = {0}; (of course you could allocate the storage space using new, which you didn't, you just declared LPCWSTR lpstr).
Extract the string and store in that buffer:
SendMessage(textBoxPathToSource, WM_GETTEXT, 256, (LPARAM)wszBuff);
and perform std::wstring s(lpStr).

EDIT: Please note the use of std::wstring, not std::string.


What ALevy said is correct, but it'd be better to use a std::vector<WCHAR> than a fixed-size buffer (or using new):

std::wstring s;
int length = SendMessageW(textBoxPathToSource, WM_GETTEXTLENGTH, 0, 0);
if (length > 0)
{
    std::vector<WCHAR> buf(length + 1 /* NUL */);
    SendMessageW(textBoxPathToSource,
                 WM_GETTEXT,
                 buf.size(),
                 reinterpret_cast<LPCWSTR>(&buf[0]));
    s = &buf[0];
}
0

精彩评论

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