在Windows控制台中更改背景和文本颜色,c ++

时间:2014-08-20 10:06:15

标签: c++ windows-console

我使用以下代码更改控制台的颜色。但它也突出了文本。我不希望我的文字突出显示并想要一个白色背景。

    using namespace std;
#include<conio.h>
#include<stdlib.h>
#include <iostream>
#include <windows.h>
using namespace std;

//returns the current attributes
WORD GetConsoleTextAttribute (HANDLE hCon)
{
  CONSOLE_SCREEN_BUFFER_INFO con_info;
  GetConsoleScreenBufferInfo(hCon, &con_info);

  return con_info.wAttributes;
}

int main (void)
{
  system("color F1");

  HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  const int saved_colors = GetConsoleTextAttribute(hConsole);



  SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_INTENSITY);
  cout << "This text should be blue" << endl;
  SetConsoleTextAttribute(hConsole, saved_colors);
  SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
  cout << "This text should be green" << endl;
  SetConsoleTextAttribute(hConsole, saved_colors);
  getch();
  return 0;
}

1 个答案:

答案 0 :(得分:0)

自己制作白色背景

WORD whiteBack = BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY;
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_INTENSITY | whiteBack);
cout << "This text should be blue" << endl;
SetConsoleTextAttribute(hConsole, saved_colors);
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_INTENSITY | whiteBack);
cout << "This text should be green" << endl;