使用字符串在 C++ 中设置控制台标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13219182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:06:04  来源:igfitidea点击:

Set console title in C++ using a string

c++windowsconsolejava-native-interfacetitle

提问by popgalop

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 SetConsoleTitlefunction 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.

我想知道如何使用字符串作为新参数在 C++ 中更改控制台标题。
我知道您可以使用SetConsoleTitleWin32 API的功能,但它不带字符串参数。
我需要这个,因为我正在做一个带有控制台效果和命令的 Java 本机界面项目。
我正在使用 Windows,它只需要与 Windows 兼容。

回答by Some programmer dude

The SetConsoleTitlefunction does indeedtake a string argument. It's just that the kindof string depends on the use of UNICODE or not.

SetConsoleTitle函数确实采用字符串参数。只是字符串的种类取决于是否使用UNICODE。

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

您必须使用例如_T宏来确保文字字符串的格式正确(宽字符或单字节):

SetConsoleTitle(_T("Some title"));

If you are using e.g. std::stringthings get a little more complicated, as you might have to convert between std::stringand std::wstringdepending on the _UNICODEmacro.

如果您使用例如,std::string事情变得有点复杂,因为您可能必须在宏之间进行转换std::stringstd::wstring根据_UNICODE宏进行转换。

One way of not having to do that conversion is to always use only std::stringif _UNICODEis not defined, or only std::wstringif it is defined. This can be done by adding a typedefin the "stdafx.h"header file:

不必进行这种转换的一种方法是始终仅std::string_UNICODE未定义时或仅std::wstring在已定义时使用。这可以通过typedef"stdafx.h"头文件中添加 a 来完成:

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

If your problem is that SetConsoleTitledoesn'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_strof the string classes to get a pointer to the string to be used with function that require old-style C strings:

如果您的问题是SetConsoleTitle不需要 a std::string(or std::wstring),那是因为它必须与没有字符串类(或根本没有类)的 C 程序兼容。在这种情况下,您可以使用c_str字符串类的 来获取指向要与需要旧式 C 字符串的函数一起使用的字符串的指针:

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

回答by Ivan Aksamentov - Drop

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