我在理解 Win32 API 中的 GetWindowTextA()
函数时遇到问题。
根据 Microsoft 文档,nMaxCount
是要复制到缓冲区 lpString
的最大字符数,包括 null字符。
那么,GetWindowTextA()
是否自动将空终止字符写入缓冲区 lpString
还是我必须手动添加空终止字符转换成 lpString
?
这是 Microsoft 文档中的 GetWindowTextA()
定义:
int GetWindowTextA(
[in] HWND hWnd,
[out] LPSTR lpString,
[in] int nMaxCount
);
代码如下:
char M_Buff[20];
SetWindowTextA(M_SEND_EDIT_TEXT,"Hello World");
GetWindowTextA(M_SEND_EDIT_TEXT,M_Buff,20); //Do i have to add the null termination caracter into M_Buff myself or it is put automatically ?
printf("String is %s\n",M_Buff);
最佳答案
如果 GetWindowTextA()
函数通过返回一个非零值来报告成功,那么它还将一个终止空字符写入内存缓冲区。无需自己添加。
official documentation of that function没有明确指定它将始终将空字符写入字符串。它只为被截断的字符串的边缘情况明确指定了这一点:
If the string is as long or longer than the buffer, the string is truncated and terminated with a null character.
但是,如果对于字符串未被截断的一般情况,该语句也没有这样做,则它没有意义。因此,可以安全地假设当字符串未被截断时它也会写入一个终止空字符。
此外,文档说明如下:
If the function succeeds, the return value is the length, in characters, of the copied string, not including the terminating null character.
该语句还暗示它将向缓冲区写入一个终止空字符。
此外,正如其他答案之一指出的那样,参数类型 LPSTR
意味着在函数返回后缓冲区将以空值终止。
关于c++ - Win32 窗口文本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73306248/