
Now, since your C++ code is already Windows-specific, that should not be a problem.Īnd, anyway, IMO the standard should be fixed to allow something like overwriting the terminating NUL with another NUL a valid well-defined operation. However, it seems to work just fine in Visual Studio (tested on both 20). However, note that overwriting the NUL terminator in STL strings with another NUL terminator seems to be "undefined behavior", at least according to this discussion on Stack"" This approach is more efficient than having a separate std::vector for buffer allocation, with a separate dynamic memory allocation, and then a deep-copy into the std::wstring. However, you have to pass the whole destination buffer length (*including* the terminating NUL) to GetWindowText() as third parameter. Note that the length value returned by GetWindowTextLength() excludes the terminating NUL. my main concern about this is to not abuse of p-invoke and keep my. If the specified window is a control, the text of the control is copied. Str.resize(len) // make enough room in string However, GetWindowText cannot retrieve the text of a control in another application, If the target window is owned by the current process, GetWindowText.

Something like this: int len = GetWindowTextLength(hwnd) Then how are you supposed to get any window text ?Īn option would be to make enough room inside the string for storing text in it.
