gpt4 book ai didi

c++ - 如何在 Windows 的 C++ 中以 char * 格式获取当前窗口的标题?

转载 作者:可可西里 更新时间:2023-11-01 13:57:49 27 4
gpt4 key购买 nike

我想在控制台和/或文件中写入当前窗口标题,但我无法将 LPWSTR 转换为 char *const char *。我的代码是:

LPWSTR title = new WCHAR();
HWND handle = GetForegroundWindow();
GetWindowText(handle, title, GetWindowTextLength( handle )+1);

/*Problem is here */
char * CSTitle ???<??? title

std::cout << CSTitle;

FILE *file;
file=fopen("file.txt","a+");
fputs(CSTitle,file);
fclose(file);

最佳答案

您只为一个字符分配了足够的内存,而不是整个字符串。当 GetWindowText 被调用时,它复制的字符多于内存,从而导致未定义的行为。您可以使用 std::string 来确保有足够的可用内存并避免自己管理内存。

#include <string>

HWND handle = GetForegroundWindow();
int bufsize = GetWindowTextLength(handle);
std::basic_string<TCHAR> title(bufsize, 0);
GetWindowText(handle, &title[0], bufsize + 1);

关于c++ - 如何在 Windows 的 C++ 中以 char * 格式获取当前窗口的标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16409282/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com