在C和C控制台输出的更改背景颜色++ [英] Change background color of console output in C and C++

查看:159
本文介绍了在C和C控制台输出的更改背景颜色++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用系统命令更改我的控制台背景和文本颜色。

I change the background and text color in my console by using the "system" command.

    #include <iostream>

using namespace std;

int main()
{
system ("color 1a");
cout <<"Hello World";

cin.ignore();
return 0;
}

有没有办法来改变颜色只有一条线? C或C ++的罚款。
谢谢你。

Is there a way to change color in only one line? C or C++ are fine. Thanks.

推荐答案

我假设你使用的是Windows,因为你的系统()函数执行颜色这是Windows控制台程序。

I assume you are using Windows, as your system() function is executing color which is a console utility for Windows.

如果你打算写你的Windows程序,并要更改文本和/或背景颜色,使用:

If you are going to write your program for Windows and you want to change color of text and/or background, use this:

   SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), attr);

其中, ATTR 是值与组合| (按位或运营商),选择您想要whther改变前景或背景色。申请变更与写入控制台下一个功能(的printf()为例)。

Where attr is a combination of values with | (bitwise OR operator), to choose whther you want to change foreground or background color. Changes apply with the next function that writes to the console (printf() for example).

有关详细说明如何连接code中的 ATTR 参数,在这里:
<一href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088%28v=vs.85%29.aspx#_win32_character_attributes\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088%28v=vs.85%29.aspx#_win32_character_attributes

Details about how to encode the attr argument, here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088%28v=vs.85%29.aspx#_win32_character_attributes

例如,这个程序打印Hello World的使用黄色文字(红+绿+强)在蓝色的背景,在计算机与Windows 2000或更高版本:

For example, this programs prints "Hello world" using yellow text (red+green+intensity) over blue background, in a computer with Windows 2000 or later:

#include <stdio.h>
#include <windows.h>

int main()
{
  SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED |
                                                            FOREGROUND_GREEN | 
                                                            FOREGROUND_INTENSITY | 
                                                            BACKGROUND_BLUE
                          );
  printf ("Hello world\n");
  return 0;
}


这等显示出了前景色和背景色的所有组合的彩色图:


This other shows a color chart showing all combinations for foreground and background colors:

#include <stdio.h>
#include <windows.h>

int main()
{
  unsigned char b,f;

  for (b=0;b<16;b++)
  {
    for (f=0;f<16;f++)
    {
        SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), b<<4 | f);
        printf ("%.2X", b<<4 | f);
    }
    printf ("\n");
  }
  SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), 0x07);
  printf ("\n");
  return 0;
}

这篇关于在C和C控制台输出的更改背景颜色++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆