使用字符串在 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
Set console title in C++ using a string
提问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 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.
我想知道如何使用字符串作为新参数在 C++ 中更改控制台标题。
我知道您可以使用SetConsoleTitle
Win32 API的功能,但它不带字符串参数。
我需要这个,因为我正在做一个带有控制台效果和命令的 Java 本机界面项目。
我正在使用 Windows,它只需要与 Windows 兼容。
回答by Some programmer dude
The SetConsoleTitle
function 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 _T
macro 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::string
things get a little more complicated, as you might have to convert between std::string
and std::wstring
depending on the _UNICODE
macro.
如果您使用例如,std::string
事情变得有点复杂,因为您可能必须在宏之间进行转换std::string
并std::wstring
根据_UNICODE
宏进行转换。
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:
不必进行这种转换的一种方法是始终仅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 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:
如果您的问题是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());