文字列を新しいパラメーターとして使用して、C++ でコンソールのタイトルを変更する方法を知りたいです。
Win32 APIの関数を使用できることは知ってSetConsoleTitle
いますが、それは文字列パラメーターを取りません。
コンソール効果とコマンドを使用して Java ネイティブ インターフェイス プロジェクトを行っているため、これが必要です。
Windows を使用していますが、Windows と互換性があれば十分です。
3 に答える
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());
There's also another solution, and that is to use the explicit narrow-character "ASCII" version of the function, which have an A
suffix:
SetConsoleTitleA("Some title");
There's of course also a wide-character variant, with a W
suffix:
SetConsoleTitleW(L"Some title");
string str(L"Console title");
SetConsoleTitle(str.c_str());