c++ - Win32 窗口文本问题

标签 c++ api winapi

我在理解 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/

相关文章:

c++ - std::equal 给出 "Term doesnt evaluate to a function taking 2 arguments"

java - 哪个 Java 数据库 API 最容易使用?

qt - 如何在无边框窗口中保持阴影

c++ - 使用 Visual C++ 编译器在 Windows 上构建库时如何正确设置目标操作系统版本

c++ - 为什么我们不需要对象来存储字符串数据?

php - 为什么我不应该基于 ZeroMQ 构建 web 服务?

php - 如何使用 mockbin API 正确创建一个 bin?

c++ - CMake 使用外部库编译

如果列结果为空,则 C++ SQLite 停止错误

c++ - 内联汇编 GCD 不起作用