How to change text color and console color in code::blocks?

后端 未结 8 1926
故里飘歌
故里飘歌 2020-12-08 17:29

I am writing a program in C. I want to change the text color and background color in the console. My sample program is -

#include 
#include &         


        
8条回答
  •  情歌与酒
    2020-12-08 18:22

    This is a function online, I created a header file with it, and I use Setcolor(); instead, I hope this helped! You can change the color by choosing any color in the range of 0-256. :) Sadly, I believe CodeBlocks has a later build of the window.h library...

    #include             //This is the header file for windows.
    #include               //C standard library header file
    
    void SetColor(int ForgC);
    
    int main()
    {
        printf("Test color");       //Here the text color is white
        SetColor(30);               //Function call to change the text color
        printf("Test color");       //Now the text color is green
        return 0;
    }
    
    void SetColor(int ForgC)
    {
         WORD wColor;
         //This handle is needed to get the current background attribute
    
         HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
         CONSOLE_SCREEN_BUFFER_INFO csbi;
         //csbi is used for wAttributes word
    
         if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
         {
              //To mask out all but the background attribute, and to add the color
              wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
              SetConsoleTextAttribute(hStdOut, wColor);
         }
         return;
    }
    

提交回复
热议问题