Работа с консолью в C# (класс Console). Украшение консоли
Нередко при разработке консольных приложений в C# необходимо каким-либо образом акцентировать внимание пользователя на отдельных частях программы. Например, выделить цветом определенный запрос на ввод данных или указать на ту или иную ошибку. Класс Console позволяет это сделать, используя специальные свойства и методы для работы с окном консоли.
Как изменить цвет текста в консоли?
Наверное, самым популярным украшением консоли является изменение цвета текста. Чтобы изменить цвет всего следующего текста в консоли, необходимо использовать свойство ForegroundColor класса Console . Свойство ForegroundColor имеет тип специального перечисления ( enum ) ConsoleColor и, в связи с этим, мы несколько ограничены в выборе цвета текста, однако и доступных цветов (а их ровно шестнадцать) нам вполне должно хватить, чтобы сделать консоль более красивой. Рассмотрим такой пример:
Здесь мы несколько раз меняем цвет текста, в зависимости от того, что мы хотим сделать: обратить внимание пользователя (красный), ввод текста (зеленый), вывод текста (синий). На экране можно увидеть следующую красочную консоль:
Чтобы продемонстрировать все имеющиеся цвета, которые мы можем использовать для консоли, можно написать вот такую простенькую программку с циклом:
На экран будут выведены все значения перечисления ConsoleColor

При этом, первая строка в консоли написана чёрным цветом на чёрном фоне, поэтому её и не видно. Именно на этом моменте мы и перейдем к следующему вопросу — как изменить цвет фона в консоли?
Как изменить цвет фона в консоли?
Для того, чтобы изменить цвет фона в консоли используется свойство BackgroundColor . Это свойство, также, как ForegroundColor принимает значения типа ConsoleColor , поэтому подробно мы на этом свойстве останавливаться не будем, а только продемонстрируем небольшой пример того, как вывести в консоль чёрный текст на белом фоне:

Как изменить цвет всего окна консоли?
Как можно заметить, в предыдущем примере цвет фона меняется только под текстом. Если же нам необходимо изменить цвет всего окна, то необходимо после присвоения свойству BackgroundColor значения очистить консоль вызвав метод Clear() . Например:
В результате увидим следующее окно консоли:

Как изменить заголовок консоли
Чтобы изменить заголовок консоли, необходимо использовать свойство Title . Например:

Итого
В этой части учебника по C# мы научились украшать консоль, используя свойства класса Console : изменять цвет текста, фона, изменять заголовок окна консоли. В следующей части рассмотрим как работать с буфером консоли.
How to set the colors of the console in Visual Studio
This post was sparked from a question on Stackoverflow that I thought was common knowledge. The question was on how to change the background color of the console in Visual Studio and not using code. In this post I will share how to customize the colors of the console that is launched when debugging or running a console application in Visual Studio.
First you need to go to the top left corner of the console, and click on the console icon shown below:
From the menu, click preferences and you will see a window like the following:
From this window open up the terminal tab. This is the place where you can change colors, for example foreground or background color:
In the blow I have changed the background color to green and the foreground to black:
It is that easy to change the colors of the console. You can also change the font size in the font tab of the preferences. I hope you enjoyed this post, let me know in the comments if you did 🙂
report this ad Peter Daugaard Rasmussen’s Picture
Is it possible to write to the console in colour in .NET?
Writing a small command line tool, it would be nice to output in different colours. Is this possible?
13 Answers 13
Yes. See this article. Here’s an example from there:

Above comments are both solid responses, however note that they aren’t thread safe. If you are writing to the console with multiple threads, changing colors will add a race condition that can create some strange looking output. It is simple to fix though:
![]()
I’ve created a small plugin (available on NuGet) that allows you to add any (if supported by your terminal) color to your console output, without the limitations of the classic solutions.
It works by extending the String object and the syntax is very simple:
Both foreground and background colors are supported.

Here is a simple method I wrote for writing console messages with inline color changes. It only supports one color, but it fits my needs.

![]()
Yes, it’s easy and possible. Define first default colors.
Console.Clear() it’s important in order to set new console colors. If you don’t make this step you can see combined colors when ask for values with Console.ReadLine() .
Then you can change the colors on each print:
When finish your program, remember reset console colors on finish:
Now with netcore we have another problem if you want to "preserve" the User experience because terminal have different colors on each Operative System.
I’m making a library that solves this problem with Text Format: colors, alignment and lot more. Feel free to use and contribute.
Colors for Windows/Linux (Dark): 
Colors for MacOS (Light): 
C# Console Color, Text and BackgroundColor
Console colors. On a console, text and background colors can be changed.
This sometimes makes programs easier to use. We change colors to make programs more expressive. Errors and alerts are more noticeable. This leads to higher quality.
Example. First, the Console has many static methods and properties on it. To see them, type "Console" and press the period. IntelliSense will show you the possible methods. Here we see BackgroundColor, ForegroundColor and ResetColor.


This program includes the System namespace, which contains the Console class. In Main, the BackgroundColor property is set to ConsoleColor.Blue. Next, ForegroundColor is set to ConsoleColor.White.
Note: The two lines, when they are printed, will both have blue backgrounds and white foregrounds.
Also: We see the ResetColor method on Console being used. This sets the colors in your Console back to their defaults.
Example 2. Often, writing an entire row of color in the Console may be helpful, either to separate output or indicate an important message. Here we refactor the Console code into a separate method.
Tip: In that method, you can change the colors, pad the string, and reset the console.

In the line of the example that uses PadRight, the parameter is the Console.WindowWidth property minus one. This returns a string that will fill up the Console's width. If you do not subtract one, it sometimes incorrectly wraps lines.
Example 3. Here, we see an original program that displays all the backgrounds and foregrounds possible with the Console. It would be interesting to nest the loops and run though all combinations. MSDN shows a similar program with more complexity.

If you run the program above, it will output this list of ConsoleColor values. You can see some of the possible values. If you choose white on blue, you may evoke memories of the BSOD (Blue Screen of Death).
Artists. If you are not a visual artist, you should probably be careful about the colors you choose. Consoles are never beautiful, but choosing red on green won't help anyone get their work done.
Instead: I suggest focusing on the structure of your output, with padding. More information on padding is available.