想写这个东西其实是因为最近要写个命令行的工具,但是有个问题是什么呢?就是传统的那个黑漆漆的窗口看起来很蛋疼。并且完全看不到重点,于是就想起来这么一个东西。相对来说针对*nix的系统方法会比较通用一些,而windows下这个东西需要用到专门的Windows相关的api来实现。
下面先说通用的方法:
1.*nix (Linux/Unix/Mac OS)
//
// main.cpp
// ColoredHelloWorld
//
// Created by obaby on 14-2-27.
// Copyright (c) 2014年 mars. All rights reserved.
//
#include
//the following are UBUNTU/LINUX ONLY terminal color codes.
#define RESET "\033[0m"
#define BLACK "\033[30m" /* Black */
#define RED "\033[31m" /* Red */
#define GREEN "\033[32m" /* Green */
#define YELLOW "\033[33m" /* Yellow */
#define BLUE "\033[34m" /* Blue */
#define MAGENTA "\033[35m" /* Magenta */
#define CYAN "\033[36m" /* Cyan */
#define WHITE "\033[37m" /* White */
#define BOLDBLACK "\033[1m\033[30m" /* Bold Black */
#define BOLDRED "\033[1m\033[31m" /* Bold Red */
#define BOLDGREEN "\033[1m\033[32m" /* Bold Green */
#define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */
#define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */
#define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */
#define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */
#define BOLDWHITE "\033[1m\033[37m" /* Bold White */
int main(int argc, const char * argv[])
{
// insert code here...
std::cout<
2.Windows下面要用到一个api叫做:SetConsoleTextAttribute方法也比较简单。
// ColordCout.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
#include
using namespace std;
void SetColor(unsigned short forecolor =4 ,unsigned short backgroudcolor =0)
{
HANDLE hCon =GetStdHandle(STD_OUTPUT_HANDLE); //获取缓冲区句柄
SetConsoleTextAttribute(hCon,forecolor|backgroudcolor); //设置文本及背景色
}
int _tmain(int argc, _TCHAR* argv[])
{
SetColor(40,30);
std::cout < <"Colored hello world for windows!\n";
SetColor(120,20);
std::cout <<"Colored hello world for windows!\n";
SetColor(10,50);
std::cout <<"Colored hello world for windows!\n";
return 0;
}