Logo Questions Linux Laravel Mysql Ubuntu Git Menu

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;
like image 401
Mehdi Yeganeh Avatar asked Mar 24 '23 08:03

Mehdi Yeganeh

1 Answers

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);
like image 95
Captain Obvlious Avatar answered Apr 25 '23 08:04

Captain Obvlious