[英]How can I get the current window's title with char * format in C++ on Windows?
I want the write the current window title in console and/or file, and I have trouble with LPWSTR
to char *
or const char *
. 我想在控制台和/或文件中写入当前窗口标题,并且在
LPWSTR
到char *
或const char *
遇到问题。 My code is: 我的代码是:
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);
You are only allocating enough memory for one character, not the entire string. 您只为一个字符而不是整个字符串分配足够的内存。 When
GetWindowText
is called it copies more characters than there is memory for causing undefined behavior. 调用
GetWindowText
,它复制的字符多于导致未定义行为的内存。 You can use std::string
to make sure there is enough memory available and avoid managing memory yourself. 您可以使用
std::string
来确保有足够的可用内存,并避免自己管理内存。
#include <string>
HWND handle = GetForegroundWindow();
int bufsize = GetWindowTextLength(handle);
std::basic_string<TCHAR> title(bufsize, 0);
GetWindowText(handle, &title[0], bufsize + 1);
You need to allocate enough memory for storing title: 您需要分配足够的内存来存储标题:
HWND handle = GetForegroundWindow();
int bufsize = GetWindowTextLength(handle) + 1;
LPWSTR title = new WCHAR[bufsize];
GetWindowText(handle, title, bufsize);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.