Set console title in C++ using a string

半世苍凉 提交于 2020-05-08 18:10:17

问题


I would like to know how to change the console title in C++ using a string as the new parameter.
I know you can use the SetConsoleTitle function of the Win32 API but that does not take a string parameter.
I need this because I am doing a Java native interface project with console effects and commands.
I am using windows and it only has to be compatible with Windows.


回答1:


The SetConsoleTitle function does indeed take a string argument. It's just that the kind of string depends on the use of UNICODE or not.

You have to use e.g. the _T macro to make sure the literal string is of the correct format (wide character or single byte):

SetConsoleTitle(_T("Some title"));

If you are using e.g. std::string things get a little more complicated, as you might have to convert between std::string and std::wstring depending on the _UNICODE macro.

One way of not having to do that conversion is to always use only std::string if _UNICODE is not defined, or only std::wstring if it is defined. This can be done by adding a typedef in the "stdafx.h" header file:

#ifdef _UNICODE
typedef std::wstring tstring;
#else
typedef std::string tstring;
#endif

If your problem is that SetConsoleTitle doesn't take a std::string (or std::wstring) it's because it has to be compatible with C programs which doesn't have the string classes (or classes at all). In that case you use the c_str of the string classes to get a pointer to the string to be used with function that require old-style C strings:

tstring title = _T("Some title");
SetConsoleTitle(title.c_str());



回答2:


string str(L"Console title");
SetConsoleTitle(str.c_str());


来源:https://stackoverflow.com/questions/13219182/set-console-title-in-c-using-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!