Set console title in C++ using a string

后端 未结 2 667
南旧
南旧 2021-01-07 06:39

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 Win3

相关标签:
2条回答
  • 2021-01-07 07:05
    string str(L"Console title");
    SetConsoleTitle(str.c_str());
    
    0 讨论(0)
  • 2021-01-07 07:14

    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());
    
    0 讨论(0)
提交回复
热议问题