Set the foreground color of console output using the Console.ForegroundColor function in C#

王林
Release: 2023-11-18 08:02:49
Original
906 people have browsed it

Set the foreground color of console output using the Console.ForegroundColor function in C#

Console output is a commonly used debugging and information display method in programs. The Console class in the C# language provides a series of methods to control the style and color of console output. Among them, the Console.ForegroundColor function is used to set the foreground color of the console output (that is, the color of the text).

To use the Console.ForegroundColor function, we first need to introduce the System namespace. The code example is as follows:

using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 设置控制台输出的前景色为红色
            Console.ForegroundColor = ConsoleColor.Red;

            // 进行输出
            Console.WriteLine("这是一段红色的文本");

            // 设置控制台输出的前景色回归默认值
            Console.ResetColor();

            // 进行输出
            Console.WriteLine("这是默认的文本颜色");

            // 保持控制台窗口打开状态
            Console.ReadLine();
        }
    }
}
Copy after login

In the above code, we first pass Console.ForegroundColor = ConsoleColor.Red Set the foreground color of the console output to red. Afterwards, when outputting through Console.WriteLine, you can see that the output text color is set to red. Immediately afterwards, return the foreground color of the console output to the default value through Console.ResetColor(). The subsequent output text color will be the default color.

Through the above code example, we can easily use C#'s Console.ForegroundColor function to set the foreground color of the console output. This is very useful in scenarios such as display of debugging information and output formatting. By flexibly setting different foreground colors, we can make the console output more readable and colorful, and improve the effect of program debugging and display.

The above is the detailed content of Set the foreground color of console output using the Console.ForegroundColor function in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!