コンソール上の自由な位置への出力、色の変更
Windows のコンソール(コマンドプロンプト)に対し、カーソル位置の指定をして好きな場所へテキスト出力をしたり、色を変えたりするサンプルです。
https://gyazo.com/948925894906c08c7586c6e1ceed768f
https://gyazo.com/849f8328cc8501fdfb7b54f333cbb5f8
code: ConsoleDebugger.cpp
// コンソール上の自由な位置に出力するサンプル(Windows環境のみ)
// 例: コンソールへのデバッグ出力を行うクラス
// 出力位置を、ラベル文字列に対応する行に固定する
class ConsoleDebugger
{
public:
enum class TextColor
{
Label,
Reset,
};
public:
ConsoleDebugger()
:
stdoutHandle_{ ::GetStdHandle(STD_OUTPUT_HANDLE) }
{
::GetConsoleScreenBufferInfo(stdoutHandle_, &csbInfo_);
originalForegroundAttr_ = csbInfo_.wAttributes & ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
originalBackgroundAttr_ = csbInfo_.wAttributes & ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
}
template <class T>
void print(StringView label, T&& value)
{
const SHORT row = items_.contains(label) ? items_label.first : static_cast<SHORT>(items_.size()); const String valueText = Format(std::forward<T>(value));
items_label = std::make_pair(row, valueText); // ラベル
setConsoleCursorPosision_(COORD(0, row));
setConsoleTextColor_(TextColor::Label);
Console << label;
// 値
setConsoleCursorPosision_(COORD(16, row));
setConsoleTextColor_(TextColor::Reset);
const size_t consoleWidth = static_cast<size_t>(csbInfo_.dwSize.X);
const auto tailLength = consoleWidth - valueText.length() - (16 + 2);
const String tail = tailLength > 0 ? String(tailLength, U' ') : U"";
Console << U": " << valueText << tail;
}
private:
void setConsoleCursorPosision_(const COORD& pos)
{
::SetConsoleCursorPosition(stdoutHandle_, pos);
}
void setConsoleTextColor_(TextColor textColor)
{
if (textColor == TextColor::Label)
{
::SetConsoleTextAttribute(stdoutHandle_, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY | originalForegroundAttr_);
}
else if (textColor == TextColor::Reset)
{
::SetConsoleTextAttribute(stdoutHandle_, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | originalForegroundAttr_);
}
}
HANDLE stdoutHandle_;
CONSOLE_SCREEN_BUFFER_INFO csbInfo_;
WORD originalForegroundAttr_;
WORD originalBackgroundAttr_;
HashTable<String, std::pair<SHORT, String>> items_;
};
void Main()
{
Scene::SetBackground(Palette::Chocolate);
// コンソールを開いておく
Console.open();
ConsoleDebugger consoleDebugger;
int n = 0;
while (System::Update())
{
consoleDebugger.print(U"テストの文字列", U"Test");
consoleDebugger.print(U"Point型", RandomPoint(1000, 1000));
consoleDebugger.print(U"RectF型", RectF{ 1, 2, 3, 4 });
if (KeySpace.down())
{
++n;
consoleDebugger.print(U"任意のタイミング", Format(U"KeySpace Pressed ", n));
Print << U"KeySpace Pressed";
}
}
}