简体   繁体   English

如何更改代码::块中的文本颜色和控制台颜色?

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

I am writing a program in C. I want to change the text color and background color in the console.我正在用 C 编写程序。我想更改控制台中的文本颜色和背景颜色。 My sample program is -我的示例程序是 -

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dos.h>
#include <dir.h>

int main(int argc,char *argv[])
{
 textcolor(25);
 printf("\n \n \t This is dummy program for text color ");
 getch();

 return 0;
}

When I compile this program code::blocks gives me an error - textcolor not defined.当我编译这个程序 code::blocks 给我一个错误 - textcolor 未定义。 Why is this so?为什么会这样? I work in a GNU GCC compiler and Windows Vista.我在 GNU GCC 编译器和 Windows Vista 中工作。 If it is not going to work what is the duplicate of textcolor.如果它不起作用,textcolor 的副本是什么。 Like that I want to change the background color of the console.就像那样,我想更改控制台的背景颜色。 The compiler gives me the same error just the name of the function is different.编译器给了我同样的错误,只是函数的名称不同。 How to change the color of the console and text.如何更改控制台和文本的颜色。 Please help.请帮忙。

I am okay even if the answer is in C++.即使答案是在 C++ 中,我也没关系。

Functions like textcolor worked in old compilers like turbo C and Dev C .textcolor这样的函数可以在像turbo CDev C这样的旧编译器中工作。 In today's compilers these functions would not work.在今天的编译器中,这些函数不起作用。 I am going to give two function SetColor and ChangeConsoleToColors .我将给出两个函数SetColorChangeConsoleToColors You copy paste these functions code in your program and do the following steps.The code I am giving will not work in some compilers.您将这些函数代码复制粘贴到您的程序中并执行以下步骤。我提供的代码在某些编译器中不起作用。

The code of SetColor is - SetColor的代码是 -

 void SetColor(int ForgC)
 {
     WORD wColor;

      HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
      CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
                 //Mask out all but the background attribute, and add in the forgournd     color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
 }

To use this function you need to call it from your program.要使用此功能,您需要从您的程序中调用它。 For example I am taking your sample program -例如,我正在使用您的示例程序 -

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dos.h>
#include <dir.h>

int main(void)
{
  SetColor(4);
  printf("\n \n \t This text is written in Red Color \n ");
  getch();
  return 0;
}

void SetColor(int ForgC)
 {
 WORD wColor;

  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                 //Mask out all but the background attribute, and add in the forgournd color
      wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
      SetConsoleTextAttribute(hStdOut, wColor);
 }
 return;
}

When you run the program you will get the text color in RED.当您运行程序时,您将获得红色的文本颜色。 Now I am going to give you the code of each color -现在我要给你每种颜色的代码——

Name         | Value
             |
Black        |   0
Blue         |   1
Green        |   2
Cyan         |   3
Red          |   4
Magenta      |   5
Brown        |   6
Light Gray   |   7
Dark Gray    |   8
Light Blue   |   9
Light Green  |   10
Light Cyan   |   11
Light Red    |   12
Light Magenta|   13
Yellow       |   14
White        |   15

Now I am going to give the code of ChangeConsoleToColors .现在我要给出ChangeConsoleToColors的代码。 The code is -代码是——

void ClearConsoleToColors(int ForgC, int BackC)
 {
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
  DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
}

In this function you pass two numbers.在此函数中,您传递两个数字。 If you want normal colors just put the first number as zero and the second number as the color.如果您想要正常颜色,只需将第一个数字设为零,将第二个数字设为颜色。 My example is -我的例子是——

#include <windows.h>          //header file for windows
#include <stdio.h>

void ClearConsoleToColors(int ForgC, int BackC);

int main()
{
ClearConsoleToColors(0,15);
Sleep(1000);
return 0;
}
void ClearConsoleToColors(int ForgC, int BackC)
{
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
 DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
} 

In this case I have put the first number as zero and the second number as 15 so the console color will be white as the code for white is 15. This is working for me in code::blocks.在这种情况下,我将第一个数字设为 0,将第二个数字设为 15,因此控制台颜色将为白色,因为白色的代码是 15。这在 code::blocks 中对我有用。 Hope it works for you too.希望它也适用于你。

You can also use rlutil :您还可以使用rlutil

  • cross platform,跨平台,
  • header only ( rlutil.h ),仅标题( rlutil.h ),
  • works for C and C++,适用于 C 和 C++,
  • implements setColor() , cls() , getch() , gotoxy() , etc.实现setColor()cls()getch()gotoxy()等。
  • License: WTFPL执照: WTFPL

Your code would become something like this:你的代码会变成这样:

#include <stdio.h>

#include "rlutil.h"

int main(int argc, char* argv[])
{
    setColor(BLUE);
    printf("\n \n \t This is dummy program for text color ");
    getch();

    return 0;
}

Have a look at example.c and test.cpp for C and C++ examples.查看example.ctest.cpp以获取 C 和 C++ 示例。

I Know, I am very late but, May be my answer can help someone.我知道,我很晚了,但是,也许我的回答可以帮助某人。 Basically it's very Simple.基本上它非常简单。 Here is my Code.这是我的代码。

#include<iostream>
#include<windows.h>
using namespace std;
int main()
{
    HANDLE colors=GetStdHandle(STD_OUTPUT_HANDLE);

    string text;
    int k;
    cout<<" Enter your Text : ";
    getline(cin,text);
    for(int i=0;i<text.length();i++)
    {
        k>9 ? k=0 : k++;

        if(k==0)
        {
            SetConsoleTextAttribute(colors,1);
        }else
        {
            SetConsoleTextAttribute(colors,k);
        }
        cout<<text.at(i);
    }
}

OUTPUT输出

This Image will show you how it works这张图片将向您展示它是如何工作的

If you want the full tutorial please see my video here: How to change Text color in C++如果您想要完整的教程,请在此处观看我的视频:如何在 C++ 中更改文本颜色

This is a function online, I created a header file with it, and I use Setcolor();这是一个在线函数,我用它创建了一个头文件,并使用了Setcolor(); instead, I hope this helped!相反,我希望这有帮助! You can change the color by choosing any color in the range of 0-256.您可以通过选择 0-256 范围内的任何颜色来更改颜色。 :) Sadly, I believe CodeBlocks has a later build of the window.h library... :) 可悲的是,我相信 CodeBlocks 有一个更高版本的 window.h 库......

#include <windows.h>            //This is the header file for windows.
#include <stdio.h>              //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;
}

textcolor function is no longer supported in the latest compilers.最新的编译器不再支持textcolor函数。

This the simplest way to change text color in Code Blocks.这是在代码块中更改文本颜色的最简单方法。 You can use system function.您可以使用system功能。

To change Text Color :要更改文本颜色:

#include<stdio.h> 
#include<stdlib.h> //as system function is in the standard library

int main()        
        {
          system("color 1"); //here 1 represents the text color
          printf("This is dummy program for text color");
          return 0;
        }

If you want to change both the text color & console color you just need to add another color code in system function如果您想同时更改文本颜色和控制台颜色,您只需要在system功能中添加另一个颜色代码

To change Text Color & Console Color :要更改文本颜色和控制台颜色:

system("color 41"); //here 4 represents the console color and 1 represents the text color

NB: Don't use spaces between color code like these注意:不要在这些颜色代码之间使用空格

system("color 4 1");

Though if you do it Code Block will show all the color codes.但是,如果您这样做,代码块将显示所有颜色代码。 You can use this tricks to know all supported color codes.您可以使用此技巧来了解所有支持的颜色代码。

You should define the function textcolor before.您应该之前定义函数 textcolor 。 Because textcolor is not a standard function in C.因为 textcolor 不是 C 中的标准函数。

void textcolor(unsigned short color) {
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon,color);
}

An Easy Approach...一个简单的方法...

system("Color F0");

Letter Represents Background Color while the number represents the text color.字母代表背景颜色,而数字代表文本颜色。

0 = Black 0 = 黑色

1 = Blue 1 = 蓝色

2 = Green 2 = 绿色

3 = Aqua 3 = 水

4 = Red 4 = 红色

5 = Purple 5 = 紫色

6 = Yellow 6 = 黄色

7 = White 7 = 白色

8 = Gray 8 = 灰色

9 = Light Blue 9 = 浅蓝色

A = Light Green A = 浅绿色

B = Light Aqua B = 浅水色

C = Light Red C = 浅红色

D = Light Purple D = 浅紫色

E = Light Yellow E = 浅黄色

F = Bright White F = 亮白

system("COLOR 0A"); ' '

where 0A is a combination of background and font color 0其中 0A 是背景和字体颜色的组合 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM