Reputation: 2141
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);
Upvotes: 4
Views: 4865
Reputation: 20103
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);
Upvotes: 4
Reputation: 731
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);
Upvotes: 3