Windows console color codes

Команда COLOR — установить цвет символов и фона консоли Windows

Команда COLOR задает цвет символов и цвет фона в окне консоли .

Формат командной строки:

COLOR [цвет фона][цвет текста]

Цвет задается шестнадцатеричной цифрой, Старший бит определяет яркость, а последующие биты — цвет :

Бит 0 — яркость
Бит 1 — красный ( R )
Бит 2 — зеленый ( G )
Бит 3 — синий ( B )

По умолчанию, используются белые буквы на черном фоне — цвет фона = 0 , цвет символов =7. Значения битов задают комбинацию цветов, так например, для желтого цвета используется установка битов 1 и 2 ( Красный и Зеленый). Команда для установки яркого синего цвета ( 9 ) на желтом фоне ( 6 ) : color 69

То же, но на ярком желтом фоне:

color F0 — черные символы на ярком белом фоне, color 0F — наоборот, белые яркие символы на черном фоне. .

Каждая цифра может иметь следующие значения:

Если в команде COLOR задана только одна цифра, то она определяет цвет символов на черном фоне (значение цвета фона воспринимается как 0 ):

COLOR 1 — синие буквы на черном фоне, как в команде COLOR 01

Если аргумент не указан, команда восстанавливает исходный набор цветов, каким он был на момент запуска CMD.EXE. Этот набор определяется из значения ключа /T, если он был задан при запуске интерпретатора CMD.EXE, или из значения параметров реестра, определяющих пользовательские настройки для интерпретатора команд:

HKEY_LOCAL_MACHINE\ SOFTWARE\ Microsoft \Command Processor\ DefaultColor — для всех пользователей.

HKEY_CURRENT_USER\ Software\ Microsoft\ Command Processor\ DefaultColor — для текущего пользователя. Значения параметров из раздела пользователя более приоритетны, по сравнению с параметрами раздела HKEY_LOCAL_MACHINE

Если параметр DefaultColor имеет значение по умолчанию ( REG_DWORD 0x00000000 ), то цветовой набор определяется значением параметра

HKEY_CURRENT_USER\ Console\ ScreenColors .

Команда COLOR возвращает значение кода ошибки ERRORLEVEL равный 1 при попытке вызова этой команды с совпадающими значениями цвета текста и цвета фона, например — COLOR 00 .

Console Color Перечисление

Определение

Задает константы, которые определяют основной цвет и цвет фона консоли. Specifies constants that define foreground and background colors for the console.

Черный цвет. The color black.

Синий цвет. The color blue.

Голубой цвет (сине-зеленый). The color cyan (blue-green).

Темно-синий цвет. The color dark blue.

Темно-голубой цвет (темный сине-зеленый). The color dark cyan (dark blue-green).

Темно-серый цвет. The color dark gray.

Темно-зеленый цвет. The color dark green.

Темно-пурпурный цвет (темный фиолетово-красный). The color dark magenta (dark purplish-red).

Темно-красный цвет. The color dark red.

Темно-желтый цвет (коричнево-желтый). The color dark yellow (ochre).

Серый цвет. The color gray.

Зеленый цвет. The color green.

Пурпурный цвет (фиолетово-красный). The color magenta (purplish-red).

Красный цвет. The color red.

Белый цвет. The color white.

Желтый цвет. The color yellow.

Примеры

В следующем примере значения ConsoleColor перечисления сохраняются в массиве, а текущие значения BackgroundColor свойств и сохраняются ForegroundColor в переменных. The following example saves the values of the ConsoleColor enumeration to an array and stores the current values of the BackgroundColor and ForegroundColor properties to variables. Затем он изменяет цвет переднего плана на каждый цвет в ConsoleColor перечислении, за исключением цвета, соответствующего текущему фону, и изменяет цвет фона на каждый цвет в ConsoleColor перечислении, за исключением цвета, соответствующего текущему переднему. It then changes the foreground color to each color in the ConsoleColor enumeration except to the color that matches the current background, and it changes the background color to each color in the ConsoleColor enumeration except to the color that matches the current foreground. (Если цвет переднего плана совпадает с цветом фона, текст не отображается.) Наконец, он вызывает ResetColor метод для восстановления исходных цветов консоли. (If the foreground color is the same as the background color, the text isn’t visible.) Finally, it calls the ResetColor method to restore the original console colors.

Читайте также:  Активация сервера удаленных рабочих столов windows server 2019

Команда COLOR: меняем цвет текста и фона в командной строке Windows

По умолчанию командная строка Windows располагает чёрным фоном с текстом белого цвета, который располагается на нём. Если такие оформление вам надоело, то, как ни странно, это можно изменить без особых усилий.

Конечно, можно изменить данные настройки через графический интерфейс системы (правой кнопкой мыши по рамке окна командной строкиСвойстваЦвета), но сегодня мы рассмотрим полезную команду COLOR, которая позволяет делать то же самое без дополнительных щелчков мышью.

Изменение цвета текста и фона в командной строке Windows.

Синтаксис команды color очень прост:

Цвета задаются шестнадцатеричными цифрами. Первая цифра отвечает за цвет фона, вторая за цвет текста. Можно использовать следующие цифры:

0 — черный;
1 — синий;
2 — зеленый;
3 — голубой;
4 — красный;
5 — лиловый;
6 — желтый;
7 — белый;
8 — серый;
9 — светло-синий;
A — светло-зеленый;
B — светло-голубой;
C — светло-красный;
D — светло-лиловый;
E — светло-желтый;
F — ярко-белый.

Указав сочетания двух цифр, мы можем задать цвет текста и фона. Например, красный на белом:

Если указать в команде одну цифру, то это будет воспринято как указание цвета текста на чёрном фоне. Например, команда

даст нам светло-зеленый текст на чёрном фоне.

Следует учитывать, что данные настройки будут действовать только пока текущее окно командной строки открыто. Но что делать, если мы хотим сохранить их на постоянной основе? В этом нам помогут два параметра реестра: DefaultColor и ScreenColors.

Для начала посмотрим на DefaultColor. Его можно задать как для отдельного пользователя:

так и для всех пользователей:

Значение параметра из раздела пользователя (HKEY_CURRENT_USER) имеют приоритет над значением параметра для всех.

По умолчанию DefaultColor имеет значение 0x00000000. Это значит, что настройки цвета определяются другим параметром:

Для установки настроек достаточно отредактировать DefaultColor или ScreenColors. Например, мы уже устанавливали красный цвет текста на белом фоне. Вписав подобное значение в реестре, можно установить эту настройку по умолчанию.

Установить одинаковые цвета текста и фона при помощи команды color нельзя. Подобная команда (например, color 55 ) возвратит значение кода ошибки ERRORLEVEL равное 1. Но вот через реестр Windows подобную глупость совершить можно.

Лиловый текст на лиловом фоне в командной строке.

К счастью, и возвратить всё на свои места в случае ошибки не составит труда. Напоминаю, что параметр ScreenColors по умолчанию принимает значение 0x00000007. Это белый текст на чёрном фоне.

Introducing the Windows Console Colortool

August 11th, 2017

Last week we announced the exciting news that Windows Console has a new default color scheme, and also promised you that we would release a tool to make it easier to change the console to your desired scheme. The Windows Console team is proud to present the ‘Colortool‘ which you can use to apply the new default color scheme, and several alternate pre-defined color schemes or even schemes of your own!

Читайте также:  Intel core i5 8gb 1tb linux

Get the Tool

You can find the tool inside of this Github repository. It’s an open source project provided under the MIT license so feel free to clone and fork it!

How to Use the Tool

After building colortool, to install it, copy colortool.exe along with the schemes folder to a local directory. Ensure that colortool .exe and the schemes folder are in the same folder! For easy use from a command line place colortool in a location that’s included in your PATH.

Changing the properties of a Window

Open up Command prompt and run:

  • colortool [ scheme name in schemes/ e.g: campbell]
  • Right click on the window title to access the ‘Properties’ dialogue box
  • Once the properties dialogue box opens press OK (which saves the color change)

A pplying a color scheme to your defaults

Open up Command prompt and run:

  • colortool -d [scheme name in schemes/]
  • Your current window will not be affected but your defaults now correspond to that theme

Applying a color scheme to both the Window and defaults

Calling ‘ colortool -b [scheme name in schemes/]’ will change both the Window’s current theme and the defaults.

For more information on the tool please read the README inside of the Github page.

Note: the new default color scheme of the Windows Console has been titled campbell, and the legacy scheme is titled cmd-legacy inside of the schemes folder.

Included Schemes

The colortool will work with any .itermcolors scheme. We have also included some useful themes inside of the schemes folder for the tool. This tool makes it easier for users to change their color scheme based on their accessibility needs, and we are excited to promote that by adding a color scheme called deuteranopia targeted towards users who have trouble distinguishing red and green. Here’s a description of each:

  • campbell : The new default color scheme for Windows Console
  • campbell-legacy : The first iteration of the campbell scheme
  • cmd-legacy : The legacy defaults of the Windows Console
  • OneHalfDark : A dark vim-airline theme by Son A. Pham
  • OneHalfLight : A light vim-airline theme by Son A. Pham
  • solarized_dark : The dark version of a popular color scheme by Ethan Schoonover
  • solarized_light : The light version of a popular color scheme by Ethan Schoonover
  • deuteranopia : A color scheme targeted towards making red and green clearer to users with red green colorblindness, and deuteranopia.

For example, here is solarized_dark:

We hope you have fun customizing the Windows Console color scheme to look just how you like it!

How-to: Use ANSI colors in the terminal

ANSI colors are available by default in Windows version 1909 or newer. See below for older versions.

Specify the color codes in a batch file by ECHOing the foreground and/or background color codes (from the following table) followed by the text to be formatted, followed by the ANSI default ( Esc[0m ) to reset the terminal back to the default colors.
These codes are the same as those used in a Unix/Linux/VT 100 terminal though the colors may be slightly different shades.

Color Foreground Background COLOR equivalent
Black BLACK █ Esc[30m Esc[40m 0
Red DARK_RED █ Esc[31m Esc[41m 4
Green DARK_GREEN █ Esc[32m Esc[42m 2
Yellow DARK_YELLOW █ Esc[33m Esc[43m 6
Blue DARK_BLUE █ Esc[34m Esc[44m 1
Magenta DARK_MAGENTA █ Esc[35m Esc[45m 5
Cyan DARK_CYAN █ Esc[36m Esc[46m 3
Light gray DARK_WHITE █ Esc[37m Esc[47m 7
Dark gray BRIGHT_BLACK █ Esc[90m Esc[100m 8
Light red BRIGHT_RED █ Esc[91m Esc[101m C
Light green BRIGHT_GREEN █ Esc[92m Esc[102m A
Light yellow BRIGHT_YELLOW █ Esc[93m Esc[103m E
Light blue BRIGHT_BLUE █ Esc[94m Esc[104m 9
Light magenta BRIGHT_MAGENTA █ Esc[95m Esc[105m D
Light cyan BRIGHT_CYAN █ Esc[96m Esc[106m B
White WHITE █ Esc[97m Esc[107m F
Bold Esc[1m
Underline Esc[4m
No underline Esc[24m
Reverse text Esc[7m
Positive text (not reversed) Esc[27m
Default Esc[0m

The Esc character in the above table must be entered with the key combination Ctrl+[
In some text editors this will appear as ^[ or Esc[

Many basic text editors do not provide a method of entering an ANSI Esc character (n.b. do not confuse this with the CMD Escape character) to work around this, either enter Esc at the command line or use an editor like Notepad++ which allows copy and paste.

The actual colors displayed are dependent on the Terminal color scheme which can be set using ColorTool.exe The new default color scheme is called campbell.ini. This was first introduced in Windows 10 clean-install version build 16257 (1709).

The color swatches on this page are based on the new COLOR defaults.

ANSI color codes do also support redirection to a text file. You may then use TYPE to display such an output file complete with colors. However if you want to easily access the raw text without any color codes e.g. for further manipulation/sorting then avoid applying any color codes until after that has been done.

Enabling ANSI colors in older versions of Windows

To use ANSI colours in the Windows terminal requires setting VirtualTerminalLevel.

VirtualTerminalLevel = 1 is now set by default for the terminal and in ConPTY.
In Windows versions 1511 through to 1903 this had to be enabled in the registry at:

Alternatively it can be enabled by calling the SetConsoleMode API with the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag.

24 bit color

The latest W10 Console has full 24-bit color support, this is primarily for Linux compatibility so the console properties page and the default Windows color mappings still use just 16 colors, there is no plan to add additional console colors to the Win32 API.

To take advantage of the new colors use ColorTool.exe and install a theme, or use the VT100 sequences described here.
When the VT100 sequences are used with a version of the Windows Console that supports 24-bit colors they will display the desired RGB color, older consoles will choose the nearest appropriate color from the existing 16 color table.

@Echo off
Echo ¤[91m This text will display in Red ¤[0m

In the above ¤ represents the Esc character.

A batch file to display the ANSI colors: EchoANSI.CMD

“In nature, light creates the color; in the picture, color creates light.
Every color shade emanates a very characteristic light — no substitute is possible”

Оцените статью