I have a Win32 Edit window (i.e. CreateWindow with classname "EDIT").
Every time I add a line to the control I append '\r\n' (i.e new line).
However, when I call WM_GETTEXT to get the text of the EDIT window, it is always missing the last '\n'.
If I add 1 to the result of WM_GETTEXTLENGTH, it returns the correct 开发者_Go百科character count, thus WM_GETTEXT returns the final '\n'.
MSDN says this about WM_GETTEXTLENGTH:
When the WM_GETTEXTLENGTH message is sent, the DefWindowProc function returns the length, in characters, of the text. Under certain conditions, the DefWindowProc function returns a value that is larger than the actual length of the text. This occurs with certain mixtures of ANSI and Unicode, and is due to the system allowing for the possible existence of double-byte character set (DBCS) characters within the text. The return value, however, will always be at least as large as the actual length of the text; you can thus always use it to guide buffer allocation. This behavior can occur when an application uses both ANSI functions and common dialogs, which use Unicode.
... but that doesn't explain the off by 1 conundrum.
Why does this occur and is safe for me to just add an unexplained 1 to the text length?
Edit
After disabling the unicode compile, I can get it working with an ASCII build, however, I would like to get this working with a UNICODE build, perhaps the EDIT window control does not behave well with UNICODE?
Try to set ES_MULTILINE
and ES_WANTRETURN
styles for your edit control.
\r
and \n
map to byte constructs, which work when you compile for ASCII.
Because \r
, \n
are not guaranteed to represent carriage return, line feed (both could map to line feed, for example), it is best to use the hexadecimal code points when building the string. (You would probably use the TCHAR functions.)
Compile for ASCII - sprintf(dest, "%s\x0D\x0A", str);
Compile for UNICODE - wsprintf(dest, "%s\0x000D\x000A", str);
When you call WM_GETTEXT to retrieve the text you might need to call WideCharToMultiByte to convert it to a certain code page or character set such as ASCII or UTF8 in order to save it to a file.
http://msdn.microsoft.com/en-us/library/aa450989.aspx
The documentation for WM_GETTEXT
says the supplied buffer has to be large enough to include the null terminator. The documentation for WM_GETTEXTLENGTH
says the return value does not include the null terminator. So you have to include room for an extra character when allocating the buffer that receives the text.
You have to add one character for your string terminator \0
character.
精彩评论