2017-04-17 118 views
0

我需要製作一個類似於Window CMD的CLI。要製作顏色命令,我使用rlutil.h中的函數rlutil::setColorrlutil::setBackgroundColor。但是,要改變所有控制檯的顏色,我必須清除屏幕(rlutil::cls()),否則只有新的輸出會隨着圖像中的變化而出現。更改控制檯顏色並將輸出保留在C++中

沒有CLS:

Without the cls

隨着CLS: Before the command After the first command - colors af

在cmd(I用於關閉@echo不顯示當前目錄): The same codes used in the cmd

這是我所做的功能:

void colors(string value) {//I recive the user's input (like in the cmd) 
    char foo[3];//I save each character in this array 
    int c_text = 0, c_bg = 0;//Variables to get the numeric value of each character 
    if(value.length() == 2) {//This is to only accept 2 characters as parameter for the command 
     strcpy(foo, value.c_str());//Copy the values of the string in the array 
     c_bg= chartoHEX(foo[0]);//Take the int value of each character 
     //(if the parameter in chartoHEX is '0', returns 0, if it's 'A', returns 10, and so on) 
     c_text = chartoHEX(foo[1]); 
     //If the function returns -1 means that the parameter wasn't an HEX number 
     if(c_text != -1 && c_bg != -1) { 
      rlutil::setColor(c_text);//Changes the text color 
      rlutil::setBackgroundColor(c_bg);//Changes the background color 
     } 
    } 
} 

當我調用該函數:

colors("0a"); 
rlutil::cls(); 
cout << "C:\\Users\\Raven>"; 

我怎能改變顏色後的輸出?

回答

1

如果您使用底層的本地Windows控制檯功能,則可以更改顏色而不影響文本。獲取控制檯句柄GetStdHandle_get_osfhandle,然後致電WriteConsoleOutputAttribute

+0

這沒有奏效,但這幫助我找到了解決方案,而不是使用'WriteConsoleOutputAttribute'我使用了'FillConsoleOutputAttribute'。不管怎麼說,還是要謝謝你。 –

+0

@ RavenH.-如何在這裏揭示解決方案? – lit

+0

FillConsoleOutputAttribute用相同的顏色填充每個單元格,WriteConsoleOutputAttribute指定數組中每個單元格的顏色。只需選擇最適合您需求的功能即可。 – Anders