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

4

我想在控制台或文件中写入当前窗口标题,但我对将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);

3
一个 WCHAR 肯定不够。无论如何,如果你需要窄字符串,为什么不直接使用 GetWindowTextA 函数呢? - chris
我需要Unicode窗口名称,LPSTR和GetWindowTextA返回Unicode窗口名称吗? - Mehdi Yeganeh
1
尝试将每个字符转换为1字节值也不会起作用。你不能直接打印宽字符或将它们写入文件吗?这是我的建议路线。我还建议您使用类似于std::wstring(C++11)或std::vector<WCHAR>而不是简单手动管理的数组。 - chris
2个回答

4

你只为一个字符分配了足够的内存,而不是整个字符串。当调用 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);

@JonathanLeffler 不需要。basic_string 处理 null 终止符号。我们只关心字符的数量。 - Captain Obvlious
@CaptainObvlious:使用 title(bufsize, 0) 可以获取窗口标题除最后一个字符外的所有字符,使用 title(bufsize + 1, 0) 可以为最后一个字符腾出空间。 - Răzvan Flavius Panda
抱歉,我的意思是应该使用GetWindowText(handle, &title[0], bufsize + 1)而不是GetWindowText(handle, &title[0], bufsize) - Răzvan Flavius Panda

3

您需要为存储标题分配足够的内存:

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

它仍然只有一个字符长度,但是它现在的值不再是0,而是以bufsize的值开始。 - chris
@Chris,这是我的错,我复制了他的代码,却忘记修改new操作。 - richselian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接