簡體   English   中英

如何將控制台輸出的文本顏色更改為紅色,但是如果從Powershell或CMD運行,則背景保持相同的顏色

[英]How can you change the text color of console output to red, but background remains the same color if ran from Powershell or CMD

在Windows中,我希望我的程序僅向該程序的一行輸出要控制台輸出的文本為紅色。 但是,無論程序是從Powershell還是cmd運行,我都希望背景保持不變。

我試過使用HANDLE

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
cout << text;

這將改變背景。 如果我匹配cmd的默認黑色背景(如果顏色是0-15),它將在Powershell中顯示帶有黑色背景的文本,而不是Powershell的默認深藍色背景。

我想要這樣,如果有人從CMD或Powershell中運行該程序,則背景顏色不會更改,但文本會更改。

感謝immibis,我得到了答案。 我需要獲取當前的控制台顏色,然后可以從那里開始。

CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
int defaultColor = 7;
int redColor = 12;
if (GetConsoleScreenBufferInfo(hConsole, &csbiInfo)) //This gets the color
{
   defaultColor = csbiInfo.wAttributes;  //This is where the current color is stored
   redColor = (defaultColor / 16) * 16 + 12;  //Keeps the background color, sets the text to red
}
SetConsoleTextAttribute(hConsole, redColor);
cout << "This is red!\n";
SetConsoleTextAttribute(hConsole, defaultColor);
cout << "Back to Normal!";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM