如何获得控制文本?



我想获得控件文本。但是这段代码返回父类名。

const wchar_t* textInput = L"Login";   
HWND btnHandle = CreateWindowEx(0, L"BUTTON", textInput, WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON,
mCoordinate.x, mCoordinate.y, mDimension.cx, mDimension.cy, parentHandle, NULL, 
(HINSTANCE)GetWindowLongPtr(parentHandle, GWLP_HINSTANCE), NULL);
wchar_t* textOutput;
int length = GetWindowTextLengthW(btnHandle);
GetWindowText(btnHandle, textOutput, length);
MessageBox(NULL, textOutput, L"Window Text", MB_OK);

如文档所述,lpStringGetWindowTextW的参数为:

接收文本的缓冲区。

API没有为您提供该缓冲区。相反,您必须将其传递进去,如下所示:

size_t length{ GetWindowTextLengthW(btnHandle) };
// Allocates a buffer for `length` characters plus a NUL terminator
std::wstring text(length, L'');
// The API promises to write a NUL terminator into the final character
// so it is safe to lie about the length
length = GetWindowTextW(btnHandle, text.data(), text.size() + 1);
// Resize in case we got less than promised
text.resize(length);
MessageBoxW(NULL, text.c_str(), L"Window Text", MB_OK);

最新更新