简体   繁体   中英

How do I write color text to the Visual Studio output window from c#?

I want to write color text to the Visual Studio output window from c#. I want to output red code from my unit tests.

I found this question while trying to figure out why some of the lines of text in my Visual Studio 2017 Output window are colored red, and how I could accomplish the same thing.

I found that I was able to get red text by writing out a line which included:

  • an instance of " Error: " (Error, colon, followed by a space)
  • (other characters can go here)
  • another instance of " Error: " (Error, colon, followed by a space)
  • (other characters can go here)
  • followed by 1 instance of " Error * " (Error, followed by a space and then some other character)
  • (other characters can go here)

An example:

Debug.WriteLine("Error: This line will be red Error: Error Jeff");

In addition to Jeff Roe I've managed to get this:

Warnings: Console.WriteLine($"Warning: Warning '{message}'");

Errors: Console.WriteLine($"Error: Error '{message}'");

在此处输入图片说明

Sadly I could not figure out how to get green output. If any1 could add this I would be super happy !

Actually there are extensions for that. I use the lite (free) version of VSCommands for Visual Studio 2010 . With the Pro version a regex could be set to make the colouring. In the lite version I add "warning" text to the debug message and it is written in light brown.

I want to write color text to the Visual Studio output window from c#. I want to output red code from my unit tests.

据我所知,Visual Studio 中的输出窗口是一个“简单文本框”类型的控件,不支持彩色文本。

SetConsoleTextAttribute(hConsole, x)

Where k is an integer color value and hConsole is a standard output handle.

More Here - easier commands

The code below works to display output in Windows Console, not to Visual Studio Output window (thanks @AnthonyLambert for correcting me).下面的代码用于在 Windows 控制台中显示输出,而不是在 Visual Studio 输出窗口中显示(感谢 @AnthonyLambert 纠正我)。

 Console.ForegroundColor = ConsoleColor.Magenta; //Choose from the Enum
 Console.WriteLine("This message is to be in Magenta!");
 Console.ResetColor();//Reset to default

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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