#include <windows.h>
SetConsoleTextAttribute( GetStdHandle(STD_OUTPUT_HANDLE), colorCode )
colorCode: 型態是 unsigned short ?
將colorCode以二進位制表示:
LRGB LRGB
前4碼是控制 background 的顏色
後4碼是控制 foreground 的顏色
L: Light (亮度)
R: Red
G: Green
B: Blue
=======================================================================
http://en.wikipedia.org/wiki/File:AdditiveColor.svg |
windows.h裡有#define一些名稱來代表數字
FOREGROUND_INTENSITY = 0000 1000
FOREGROUND_RED = 0000 0100
......
BACKGROUND_GREEN = 0010 0000
BACKGROUND_BLUE = 0001 0000
像混三原光一樣,調整自己想要的顏色
比方說我要顯示前景亮黃色:
colorCode = 0000 1110 //這是二進位制
或
colorCode =
FOREGROUND_INTENSITY |
FOREGROUND_RED |
FOREGROUND_GREEN
下面的code用到了macro和bitwise的技巧
================================================================================
/**ConsoleColorTest.c*/
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define setColor(var)\
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BinaryStringToUShort(var))
#define setColor2(var)\
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BinaryStringToUShort(#var))
unsigned short BinaryStringToUShort( char s[] );
int main( void )
{
// back fore
// LRGB LRGB
setColor( "1010 1101" );
printf("Red + Blue = Magenta.\n");
setColor2( 0010 1001 );
printf("Light Blue.\n");
setColor2( 0000 0111 );
printf("White.\n");
system("pause");
return 0;
}
unsigned short BinaryStringToUShort( char s[] )
{
unsigned short i, sum;
sum = 0;
for( i = 0; s[i] != '\0'; i++ )
{
if( s[i]==' ' ) // skip space
continue;
if( s[i]=='1' )
++sum;
sum<<=1; // sum*=2;
}
sum>>=1; // sum/=2;
return sum;
}
======================================================================
Output:
沒有留言:
張貼留言