SetConsoleTextAttribute和SetConsoleScreenBufferInfoEx的使用
主要是作用于控制台文本下划线和改变文本颜色
#include "pch.h" #include <iostream> #include <Windows.h> #include <stdio.h> typedef CONSOLE_SCREEN_BUFFER_INFOEX CSBI; void test1() { printf("Code 1:\n"); HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); DWORD mode = 0; int flag = 1; flag &= GetConsoleMode(out, &mode); flag &= SetConsoleMode(out, mode | ENABLE_LVB_GRID_WORLDWIDE); //7 is the default foreground - gray SetConsoleTextAttribute(out, 7 | COMMON_LVB_UNDERSCORE); printf("Hello World! 1==%d", flag); getchar(); SetConsoleTextAttribute(out, 7); printf("Goodbye World! 1==%d", flag); getchar(); } void test2() { printf("Code 2:\n"); HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); DWORD mode = 0; int flag = 1; flag &= GetConsoleMode(out, &mode); flag &= SetConsoleMode(out, mode | ENABLE_LVB_GRID_WORLDWIDE); CSBI csbi = { 0 }; csbi.cbSize = sizeof(csbi); flag &= GetConsoleScreenBufferInfoEx(out, &csbi); csbi.wAttributes |= COMMON_LVB_UNDERSCORE; flag &= SetConsoleScreenBufferInfoEx(out, &csbi); printf("Hello World! 1==%d", flag); getchar(); csbi.wAttributes &= ~COMMON_LVB_UNDERSCORE; flag &= SetConsoleScreenBufferInfoEx(out, &csbi); printf("Goodbye World! 1==%d", flag); getchar(); } void test3() { // CONSOLE_SCREEN_BUFFER_INFOEX info; // info.cbSize = sizeof(info); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // GetConsoleScreenBufferInfoEx(hConsole, &info); // info.ColorTable[14] = RGB(255, 128, 0); // Replace yellow // SetConsoleScreenBufferInfoEx(hConsole, &info); SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN); printf("Hello World!----Start\n"); printf("Hello World!\n"); printf("Hello World!\n"); printf("Hello World!\n"); printf("Hello World!\n"); printf("Hello World!\n"); printf("Hello World!----End\n"); getchar(); } void test4() { 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 printf("Hello World!----Start\n"); printf("Hello World!\n"); printf("Hello World!\n"); printf("Hello World!\n"); printf("Hello World!\n"); printf("Hello World!\n"); printf("Hello World!----End\n"); getchar(); } int main() { test1(); test2(); test3(); test4(); return 0; }