Nếu như trong C/C++ chúng ta phải xây dựng 1 hàm để thực hiện việc này ( xem lại bài viết tại đây: Lập trình C/C++ – Đổi màu Console ), thì trong C# để đổi màu chữ của console rất dễ dàng.

Console.ForegroundColor = {{ Kiểu dữ liệu enum <<ConsoleColor>>}}

Đây là kiểu dữ liệu enum ConsoleColor, nó chứa những màu mà Console có thể thay đổi màu chữ được.

// Summary:
//     Specifies constants that define foreground and background colors for the console.
public enum ConsoleColor
{
     //
     // Summary:
     //     The color black.
     Black = 0,
     //
     // Summary:
     //     The color dark blue.
     DarkBlue = 1,
     //
     // Summary:
     //     The color dark green.
     DarkGreen = 2,
     //
     // Summary:
     //     The color dark cyan (dark blue-green).
     DarkCyan = 3,
     //
     // Summary:
     //     The color dark red.
     DarkRed = 4,
     //
     // Summary:
     //     The color dark magenta (dark purplish-red).
     DarkMagenta = 5,
     //
     // Summary:
     //     The color dark yellow (ochre).
     DarkYellow = 6,
     //
     // Summary:
     //     The color gray.
     Gray = 7,
     //
     // Summary:
     //     The color dark gray.
     DarkGray = 8,
     //
     // Summary:
     //     The color blue.
     Blue = 9,
     //
     // Summary:
     //     The color green.
     Green = 10,
     //
     // Summary:
     //     The color cyan (blue-green).
     Cyan = 11,
     //
     // Summary:
     //     The color red.
     Red = 12,
     //
     // Summary:
     //     The color magenta (purplish-red).
     Magenta = 13,
     //
     // Summary:
     //     The color yellow.
     Yellow = 14,
     //
     // Summary:
     //     The color white.
     White = 15
}

Ví dụ:

using System;

namespace Console_ChangeColor
{
    class MainClass
    {
        public static void Main()
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Day là dong chu co mau do");

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Day la dong chu co mau vang");

            Console.ReadKey();
        }
    }
}

Ta sẽ có kết quả như sau:

Trong bài viết tiếp theo, mình sẽ hướng dẫn những cách để tùy chỉnh console trong C# hay ho hơn như: thay đổi tiêu đề, kích thước console, thay đổi con trỏ chuột, dùng tiếng Việt trong console,….

Cảm ơn bạn đã xem bài viết, hãy để lại ý kiến của bạn để mình hoàn thiện hơn nhé!

Được phân loại:

Được gắn thẻ:

,