简体   繁体   English

如何在Windows上的C ++中以char *格式获取当前窗口的标题?

[英]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 * . 我想在控制台和/或文件中写入当前窗口标题,并且在LPWSTRchar *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.

相关问题 如何在 C++ 中的字符串中转换字符数组? - How Can I transform a array of char's in a string in C++? 窗口标题 C++ 如何获取随机标题的名称 - Window title C++ how to get the name of a randomizing title 在C ++中,如何获取当前线程的调用堆栈? - In C++, how can I get the current thread's call stack? 如何在C ++中获得以毫秒为单位的当前时间? - How can I get current time of day in milliseconds in C++? 如何获得外部应用程序列表视图的HWND? 在Windows Api中使用c ++ - How can i get HWND of external application's listview? In Windows Api using c++ 如何从 Windows 套接字 (C++) 获取连接主机的 IP 地址? - How can I get the connected host's IP address from a Windows Socket (C++)? 如何在Windows上使用c ++获取设备的父级? - How do I get a device's parent in c++ on windows? 如何从 C 或 C++ 系统中获取当前本地格式日期,可以在所有平台上运行 - How to get current local format date from system in C or C++ which can be run on all platforms 使用用户的“区域和语言”格式将Windows SYSTEMTIME转换为C ++中的字符串或char buf? - convert Windows SYSTEMTIME to a string or char buf in C++ with user's “Region and Language” format? 如何获得C ++ Windows服务的安装目录? - How can I get the installed directory for a C++ Windows Service?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM