We have the code:

Console.Write ("Что то"); 

I need that “What” be green and “that” red. Yes, it can be divided.

 Console.ForegroundColoe = ConsoleColor.Green; Console.Write ("Что"); Console.ForegroundColor = ConsoleColor.Red; Console.Write ("то"); 

But I would like to change the color of the console "in the middle" of output to the console. What is it for? Depending on the condition, we need to output some values ​​to the console again. For example, (red) 1 (green) 23, (green) 1 (red) 2 (green) 3, (green) 12 (red) 3. If they were needed in the same color, then everything is simple:

 Console.Write(new string ('123', колвораз)); 

And so ... Yes, you can create several if, and ... (Example)

 int writecount = 0; if(чтото = чтото) { do { Console.ForegroundColor = ConsoleColor.Red Console.Write("1"); Console.Fore... ++writecount; }while(writecount != чтото); 

But my application is not the easiest, and a great repetition of do (and I have big numbers there) just hangs the console tightly. How can I insert a color into the output? Or tell me another solution to this problem, preferably as resource-consuming as possible.

  • Most likely, I did not understand you correctly, but I have the following idea: Set a color for a certain group of numbers (words), for example, 1,3,5,7 - green, 2.4.6.8 - red, etc. Well, after you can already set a condition, if such a group was red, then change to a different color - Dmitry
  • No need to specify the language in the title, for this there is a label. - Nick Volynkin
  • one
    No, what you want out of the box is not. Actually, all you can do is transfer the separate output to a separate class (two solutions have already been proposed), but in any case it will be the same separate output and color switching on demand. - rdorn
  • Well, look at it again, there are described almost all the problems with the console that need to be solved, and there are tips on how to solve. The main reason for slow work in console applications is the output speed of the console itself. If you didn’t optimize the console output, there will be brakes. - rdorn

3 answers 3

As an option:

 using System; namespace ColourOutput { public static class ColourWriter { public static ConsoleColor defaultColor { get; set; } = ConsoleColor.White; public static void Write(string text) { foreach (var word in text.Split(',', ' ')) { if (word[0] == '{') { ColorHelper(word.Substring(3, word.Length - 3), word[1]); } else { Console.Write(word + " "); } } } private static void ColorHelper(string word, char color) { switch (color) { case 'G': Console.ForegroundColor = ConsoleColor.Green; Console.Write(word + " "); Console.ForegroundColor = defaultColor; break; case 'R': Console.ForegroundColor = ConsoleColor.Red; Console.Write(word + " "); Console.ForegroundColor = defaultColor; break; case 'B': Console.ForegroundColor = ConsoleColor.Blue; Console.Write(word + " "); Console.ForegroundColor = defaultColor; break; } } } class Program { static void Main(string[] args) { ColourWriter.Write("{G}Зеленый,{R}Красный - {B}Это цвета \n (С)"); Console.ReadKey(); } } } 

I think you will bring it to a usable type)

enter image description here

  • MB, I did not understand anything, but I swear in Main on ColorWriter.Write. The name "ColourWriter" does not exist in this context. - SKProCH

I'm not sure that I understood your idea, but you won't put a lot of code in the comments, so I'll write it off as an answer.

I made a small non-thread safe writer with color to the console (with buffer)

 class ColoredConsoleWriter { private List<WriteItem> _inner = new List<WriteItem>(); public void Append(string text, ConsoleColor color) { var last = _inner.LastOrDefault(); if (last != null && last.Color == color) { last.Text+=text; return; } _inner.Add(new WriteItem() {Text=text, Color = color}); } public void AppendLine(string text, ConsoleColor color) { Append(text + Environment.NewLine, color); } public void Flush() { var local = _inner; foreach (var item in local) { Console.ForegroundColor = item.Color; Console.Write(item.Text); } _inner = new List<UserQuery.ColoredConsoleWriter.WriteItem>(); } class WriteItem { public string Text { get; set; } public ConsoleColor Color { get; set;} } } 

Filled it with 10,000 text elements

 void Sample() { var writer = new ColoredConsoleWriter(); var random = new Random(); var colors = Enum.GetValues(typeof(ConsoleColor)).OfType<ConsoleColor>().ToArray(); for (var i = 0; i < 10000; i++) { writer.Append(i.ToString(), colors[random.Next(colors.Length)]); } writer.Flush(); } 

I started all this stuff

 void Main() { var sw = new Stopwatch(); sw.Start(); Sample(); sw.Stop(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(); Console.WriteLine($"Elapsed: {sw.Elapsed}"); } 

Worked in about a second result

Hope this helps you a little :)

  • в коммент много кода не засунешь thrust a в коммент много кода не засунешь - there’s no reason why you don’t put the answers in the comments. :) - Nick Volynkin
  • 3
    By the way, the picture looks soulful. - Nick Volynkin
  • @NickVolynkin I'm just not sure that this is exactly what the author is asking. And the picture and I like it myself :) - tym32167
  • @ tym32167 Yes it is. The picture is really soulful. - SKProCH

You can try the control characters . They are supported in the latest versions of Windows Tens. But first, their support should be included (I took an example from here ).

 using System; using System.Runtime.InteropServices; namespace ConApp1 { class Program { const int STD_OUTPUT_HANDLE = -11; const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4; [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll")] static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode); [DllImport("kernel32.dll")] static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode); static void Main(string[] args) { var handle = GetStdHandle(STD_OUTPUT_HANDLE); uint mode; GetConsoleMode(handle, out mode); mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; SetConsoleMode(handle, mode); const string UNDERLINE = "\x1B[4m"; const string RESET = "\x1B[0m"; const string RED = "\x1b[31m"; const string GREEN = "\x1b[32m"; Console.WriteLine("Some " + UNDERLINE + "underlined" + RESET + " text"); Console.WriteLine(RED + "Привет " + GREEN + "Мир!" + RESET); } } }