我需要通過 C 中的已知坐標獲取背景顏色。我嘗試使用 windows.h 中的 ReadConsoleOutputAttribute,但我沒有作業。這是我的代碼:
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD count;
COORD cursor = { this->X, this->Y };
LPWORD *lpAttr = new LPWORD;
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(console, &info);
ReadConsoleOutputAttribute(console, *lpAttr, 1, cursor, &count);
這里有什么問題以及解決方法是什么?我是否想從 lpAttr 或什么獲取背景顏色?
uj5u.com熱心網友回復:
顏色屬性由兩個十六進制數字指定——第一個對應于背景;第二個前景。每個數字可以是以下任何值:
0 = Black 8 = Gray 1 = Blue 9 = Light Blue 2 = Green A = Light Green 3 = Aqua B = Light Aqua 4 = Red C = Light Red 5 = Purple D = Light Purple 6 = Yellow E = Light Yellow 7 = White F = Bright White
我們只需要提取十六進制結果的第一個數字就可以知道當前坐標的背景顏色。這是我的測驗代碼。我修改了滑鼠坐標點以簡化測驗。
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
//color set test
system("color F0");
std::cout << "Hello World!\n" << endl;
HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
if (!Console)
return 0;
CONSOLE_SCREEN_BUFFER_INFO buf;
GetConsoleScreenBufferInfo(Console, &buf);
WORD Attr;
DWORD Count;
COORD pos = buf.dwCursorPosition;
ReadConsoleOutputAttribute(Console, &Attr, 1, pos, &Count);
//hexadecimal out
cout << hex << Attr << endl;
if (Attr)
{ //extract the first digit of the hexadecimal result
int color = Attr / 16;
switch (color)
{
case 0:cout << " background color is Black. " << endl; break;
case 1:cout << " background color is Blue. " << endl;break;
case 2:cout << " background color is Green . " << endl; break;
case 3:cout << " background color is Aqua. " << endl; break;
case 4:cout << " background color is Red. " << endl; break;
case 5:cout << " background color is Purple . " << endl; break;
case 6:cout << " background color is Yellow. " << endl; break;
case 7:cout << " background color is White. " << endl; break;
case 8:cout << " background color is Gray . " << endl; break;
case 9:cout << " background color is Light Blue." << endl; break;
case 10:cout << " background color is Light Green." << endl; break; //A
case 11:cout << " background color is Light Aqua ." << endl; break; //B
case 12:cout << " background color is Light Red . " << endl; break; //C
case 13:cout << " background color is Light Purple . " << endl; break; //D
case 14:cout << " background color is Light Yellow . " << endl; break; //E
case 15:cout << " background color is Bright White . " << endl; break; //F
default:
cout << " error color " << endl;
break;
}
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/460355.html