1

我只想更改控制台应用程序的前景色文本,而不是背景文本颜色或控制台背景色。换句话说:我想保持以前的颜色,除了前景文本颜色。

目前我使用下面的代码,但文本下的背景也发生了变化。

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

int main(int argc, char* argv[])
{

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN);
    cout << "green?" << endl;
    cin.ignore();
    return 0;
}
4

2 回答 2

3

Use GetConsoleScreenBufferInfoEx to retrieve the current colour attributes, and change the foreground only.

The following, albeit untested, should work no matter what background colour you start off with:

HANDLE outputHandle = GetStdHandle (STD_OUTPUT_HANDLE); //used twice
CONSOLE_SCREEN_BUFFER_INFOEX cbie; //hold info

//article didn't say this was necessary, but to be on the safe side...
cbie.cbSize = sizeof (CONSOLE_SCREEN_BUFFER_INFOEX);

GetConsoleScreenBufferInfoEx (outputHandle, &cbie); //get info

//first, cancel out all foreground attributes
//then, set the ones you want (I use bright red)
cbie.wAttributes &= 
    ~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
cbie.wAttributes |= (FOREGROUND_RED | FOREGROUND_INTENSITY);

SetConsoleScreenBufferInfoEx (outputHandle, &cbie); //pass updated info back
于 2012-05-05T16:14:37.110 回答
1

还要设置背景颜色(否则会变成黑色)例如:红色背景上的绿色书写(注意:使用按位或运算符 | )

SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | BACKGROUND_RED);
于 2012-05-05T16:02:21.873 回答