使用字符串在 C++ 中设置控制台标题
我想知道如何在 C++ 中使用字符串作为新参数来更改控制台标题.
我知道您可以使用 Win32 API 的 SetConsoleTitle
函数,但它不需要字符串参数.
我需要这个,因为我正在做一个带有控制台效果和命令的 Java 原生界面项目.
我使用的是 Windows,它只需要与 Windows 兼容.
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.
推荐答案
SetConsoleTitle
函数确实 采用字符串参数.只是字符串的种类取决于是否使用UNICODE.
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.
你必须使用例如T
宏以确保文字字符串的格式正确(宽字符或单字节):
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"));
如果您正在使用例如std::string
事情变得有点复杂,因为您可能需要在 std::string
和 std::wstring
之间进行转换,具体取决于UNICODE
宏.
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.
不必进行这种转换的一种方法是,如果未定义 UNICODE
,则始终仅使用 std::string
,或者仅使用 std::wstring
如果已定义.这可以通过在 stdafx.h"
头文件中添加 typedef
来完成:
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
如果您的问题是 SetConsoleTitle
不采用 std::string
(或 std::wstring
),那是因为它具有与没有字符串类(或根本没有类)的 C 程序兼容.在这种情况下,您使用 c_str
的字符串类来获取指向要与需要旧式 C 字符串的函数一起使用的字符串的指针:
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());
还有另一种解决方案,那就是使用显式的窄字符ASCII".函数的版本,有一个 A
后缀:
SetConsoleTitleA("Some title");
当然还有一个宽字符变体,带有 W
后缀:
There's of course also a wide-character variant, with a W
suffix:
SetConsoleTitleW(L"Some title");
相关文章