Mac OS效果
Windows 效果
想写这个东西其实是因为最近要写个命令行的工具,但是有个问题是什么呢?就是传统的那个黑漆漆的窗口看起来很蛋疼。并且完全看不到重点,于是就想起
来这么一个东西。相对来说针对*nix的系统方法会比较通用一些,而windows下这个东西需要用到专门的Windows相关的api来实现。
下面先说通用的方法:
1.*nix (Linux/Unix/Mac OS)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
//
// main.cpp
// ColoredHelloWorld
//
// Created by obaby on 14-2-27.
// Copyright (c) 2014年 mars. All rights reserved.
//
#include <iostream>
//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< <RED <<"Hello, World! in RED\n";
std::cout<<GREEN <<"Hello, World! in GREEN\n";
std::cout<<YELLOW <<"Hello, World! in YELLOW\n";
std::cout<<BLUE <<"Hello, World! in BLUE\n";
std::cout<<MAGENTA <<"Hello, World! in MAGENTA\n";
std::cout<<CYAN <<"Hello, World! in CYAN\n";
std::cout<<WHITE <<"Hello, World! in WHITE\n";
std::cout<<BOLDRED <<"Hello, World! in BOLDRED\n";
std::cout<<BOLDCYAN <<"Hello, World! in BOLDCYAN\n";
return ;
}
|
2.Windows下面要用到一个api叫做:SetConsoleTextAttribute方法也比较简单。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
// ColordCout.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <windows .h>
using namespace std;
void SetColor(unsigned short forecolor = ,unsigned short backgroudcolor =)
{
HANDLE hCon =GetStdHandle(STD_OUTPUT_HANDLE); //获取缓冲区句柄
SetConsoleTextAttribute(hCon,forecolor|backgroudcolor); //设置文本及背景色
}
int _tmain(int argc, _TCHAR* argv[])
{
SetColor(,);
std::cout < <"Colored hello world for windows!\n";
SetColor(,);
std::cout <<"Colored hello world for windows!\n";
SetColor(,);
std::cout <<"Colored hello world for windows!\n";
return ;
}
|