[英]How can I get the current window's title with char * format in C++ on Windows?
我想在控制台和/或文件中寫入當前窗口標題,並且在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);
您只為一個字符而不是整個字符串分配足夠的內存。 調用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);
您需要分配足夠的內存來存儲標題:
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.