[C ++] Windows에서 C ++를 사용한 컬러 콘솔 출력
여기 에서이 코드를 가져 왔습니다 .
// color your text in Windows console mode
// colors are 0=black 1=blue 2=green and so on to 15=white
// colorattribute = foreground + background * 16
// to get red text on yellow use 4 + 14*16 = 228
// light red on yellow would be 12 + 14*16 = 236
// a Dev-C++ tested console application by vegaseat 07nov2004
#include <iostream>
#include <windows.h> // WinApi header
using namespace std; // std::cout, std::cin
int main()
{
HANDLE hConsole;
int k;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// you can loop k higher to see more color choices
for(k = 1; k < 255; k++)
{
// pick the colorattribute k you want
SetConsoleTextAttribute(hConsole, k);
cout << k << " I want to be nice today!" << endl;
}
cin.get(); // wait
return 0;
}
-------------------Windows에서 C ++ 출력의 색상 지정은 SetConsoleTextAttribute를 통해 수행됩니다. 여기서 콘솔의 HANDLE은 속성과 함께 전달됩니다. 그러나 SetConsoleTextAttribute를 호출하는 것은 번거 롭습니다. 다행히도 인터넷과 github에 도움이 될 수있는 작은 라이브러리가 많이 있습니다. 원하는 API로 하나만 선택하면됩니다. operator <<로 색상을 변경하려면이 헤더 전용 라이브러리 https://github.com/ikalnitsky/termcolor를 권장합니다 . API는 다음과 같습니다.
using namespace termcolor;
std::cout << grey << "grey message" << reset << std::endl;
std::cout << red << "red message" << reset << std::endl;
색상을 재설정해야하는 경우 꺼져 있으면 내 라이브러리를 사용해보십시오. ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ ㅇㅇㅇ 헤더 전용이며 Windows 전용이며 https://github.com/jrebacz/colorwin에서 쉽게 printf 문에 색상을 지정할 수 있습니다 . API는 다음과 같습니다.
using namepsace wincolor;
std::cout << color(gray) << "grey message\n";
std::cout << color(red) << "red message\n";
std::cout << "normal color\n";
{
withcolor scoped(red);
std::cout << "|red\n";
std::cout << "|red again\n";
}
std::cout << "normal color\n";
withcolor(cyan).printf("A cyan printf of %d\n", 1234);
-------------------사내 솔루션은 다음과 같습니다.
inline void setcolor(int textcol, int backcol)
{
if ((textcol % 16) == (backcol % 16))textcol++;
textcol %= 16; backcol %= 16;
unsigned short wAttributes = ((unsigned)backcol << 4) | (unsigned)textcol;
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
SetConsoleTextAttribute(hStdOut, wAttributes);
}
선택할 수있는 색상의 예는 다음과 같습니다.
#define LOG_COLOR_WHITE 7
#define COLOR_GREEN 10
#define COLOR_YELLOW 14
#define COLOR_MAGENTA 13
-------------------다음과 같이 사용되는 system ( "") 명령을 사용할 수 있습니다.
cout<<"lol";
system("color 1") // the colours are from 1 to 15.
cout<<"Coloured text! yay";
출처
https://stackoverflow.com/questions/39969979