如何在 Windows 上获取C++ 个字符 * 格式的当前窗口标题?

How can I get the current window's title with char * format in C++ on Windows?

本文关键字:格式 窗口标题 字符 Windows C++ 获取      更新时间:2023-10-16

我想在控制台和/或文件中写入当前窗口标题,并且我有LPWSTRchar *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);

你需要分配足够的内存来存储标题:

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