简体   繁体   中英

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 * . 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. You can use std::string to make sure there is enough memory available and avoid managing memory yourself.

#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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM