Win32控制台几乎是每个C/C++程序员都用过的。以前只在cmd中改过字体颜色。向往电影中的hack可以在黑色的窗口敲出亮绿色的代码,感觉很牛X。我简单封装了Windows的函数。为了方便大家修改我在函数的名称前增加了KXL_方便替换。
KxlConsoleFunction.h
#ifndef KXL_CONSOLEFUNCTION_H_
#define KXL_CONSOLEFUNCTION_H_
#include <Windows.h>
#include <iostream>
using namespace std;
bool KXL_SetConsoleTextColor(__in WORD wAttributes = FOREGROUND_GREEN | FOREGROUND_INTENSITY);
void KXL_SetConsoleTextColor_Test();
#endif
KxlConsoleFunction.cpp
#include "KxlConsoleFunction.h"
#include <Windows.h>
#include <iostream>
using namespace std;
bool KXL_SetConsoleTextColor(__in WORD wAttributes)
{
if(wAttributes > 256)
{
return false;
}
HANDLE hFGetStdHandleRetVal = 0;
hFGetStdHandleRetVal = GetStdHandle(STD_OUTPUT_HANDLE);
if(INVALID_HANDLE_VALUE == hFGetStdHandleRetVal)
{
printf("Error Number: %d\n", GetLastError());
return false;
}
int nFSetConsoleTextAttributeRetVal = 0;
nFSetConsoleTextAttributeRetVal = SetConsoleTextAttribute(hFGetStdHandleRetVal, wAttributes);
if(0 == nFSetConsoleTextAttributeRetVal)
{
printf("Error Number: %d\n", GetLastError());
return false;
}
return true;
}
void KXL_SetConsoleTextColor_Test()
{
printf("========================================\n");
printf("\t控制台颜色设置函数演示开始\n\n");
printf("\t\t-- By 寇香龙\n");
printf("----------------------------------------\n");
KXL_SetConsoleTextColor();
printf("使用默认颜色\n");
KXL_SetConsoleTextColor(BACKGROUND_BLUE | FOREGROUND_RED);
printf("背景色为蓝色 前景色为红色\n");
KXL_SetConsoleTextColor(0| FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
printf("演示所有颜色组合\n");
for(int i = 0; i < 256; i ++)
{
KXL_SetConsoleTextColor(i);
printf("颜色%d\t",i);
}
KXL_SetConsoleTextColor(0| FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
printf("\n========================================\n");
}
main.cpp
#include "KxlConsoleFunction.h"
int main()
{
KXL_SetConsoleTextColor_Test();
getchar();
return 0;
}
程序执行结果