Color your Console text (C#)

vegaseat 0 Tallied Votes 1K Views Share

This short piece of code shows you how to display text in color in a C# windows console program. The corresponding WIN32 API functions are in the kernel32.dll and are imported and declared external. The only other problem is to assign variable types that accommodate the types listed in the Win32 API help file.

Ketsuekiame commented: Overly complicated PInvoke for a very simple task. .NET allows you to accomplish this with minimal effort. -2
// change text color in Windows console mode
// colors are 0=black 1=blue 2=green 4=red and so on to 15=white  
// colorattribute = foreground + background * 16
// to get red text on yellow use 4 + 14*16 = 228
// light red on yellow would be 12 + 14*16 = 236
//
// the necessary WinApi functions are in kernel32.dll
// in C# Handle = IntPtr  DWORD = uint   WORD = int
// STD_OUTPUT_HANDLE = 0xfffffff5 (from winbase.h)
//
// a Console Application tested with VCS.NET 2003

using System;
using System.Runtime.InteropServices; // DllImport() 

namespace TextColor1
{
	class MainClass
	{
	  [DllImport("kernel32.dll")]
    public static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput,
      int wAttributes);
	  [DllImport("kernel32.dll")]
    public static extern IntPtr GetStdHandle(uint nStdHandle);
    
		public static void Main(string[] args)
		{
			uint STD_OUTPUT_HANDLE = 0xfffffff5;
		  IntPtr hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
		  // increase k for more color options
		  for (int k = 1; k < 255; k++)
		  {
        SetConsoleTextAttribute(hConsole, k);
		    Console.WriteLine("{0:d3}  I want to be nice today!",k);
		  }
		  // final setting
		  SetConsoleTextAttribute(hConsole, 236);
		  
		  Console.WriteLine("Press Enter to exit ...");
      Console.Read();  // wait
		}
	}
}
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sorry, finally got it right
4 + 14*16 = 228

catapult 0 Newbie Poster

Change Console Color in C#

using System;
using System.Runtime.InteropServices; // DllImport() needed to change the backgr color

namespace color_console
{
    class MainClass
    {
        // DllImport - change the backgr color
        [DllImport("kernel32.dll")]        public static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, int wAttributes);
        [DllImport("kernel32.dll")]        public static extern IntPtr GetStdHandle(uint nStdHandle);


        public static void Main(string[] args)
        {


            //use white font and change bckgr color to blue
            uint STD_OUTPUT_HANDLE = 0xfffffff5; 
            IntPtr hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
            SetConsoleTextAttribute(hConsole, 15); 
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.Clear();
            // THAT WAS ALL the code needed to change the background color


            // print something 
            Console.WriteLine("Hello World!\n\nPress Enter to continue...");
            Console.Read();


            //the rest of the code...







            // OTHER EXAMPLES of color background
            String[] colorNames = ConsoleColor.GetNames(typeof(ConsoleColor));

            // cannot print all colors under ConsoleColor, only 10 out of 16
            for (int x = 0; x < colorNames.Length; x++)
            {

                Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorNames[x]);
                Console.Clear();

                        // this is just to ptrint on white background wiht coloured font
                    if (Console.BackgroundColor == ConsoleColor.White)
                    { Console.ForegroundColor = ConsoleColor.Blue; }

                Console.Write("This is background color {0}.", colorNames[x]); 
                Console.WriteLine("\n\nPress Enter to continue...");
                Console.Read();
            }





            // next section shows different combinations of font and font_backgr colors

            Console.BackgroundColor = ConsoleColor.White;
            Console.Clear();

            // increase k for more color options
            for (int k = 1; k < 255; k++)
            {
                SetConsoleTextAttribute(hConsole, k);
                Console.WriteLine("{0:d3} coloured font wiht background !", k);
            }

            // final setting
            SetConsoleTextAttribute(hConsole, 236);   

        }
    }
}
armando.miani 0 Newbie Poster

Why don't use:

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Printing in red...");

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Printing in green...");

Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Printing in blue...");
zempf13 0 Newbie Poster

This lets you set the foreground and background color without having to guess which number to use.

ConsoleColor foreground = ConsoleColor.Gray;
ConsoleColor background = ConsoleColor.Red; 
SetConsoleTextAttribute(hConsole, (int)foreground | ((int)background << 4));
KrayZVIII 0 Newbie Poster
static void main();
{
   //First
   Console.Clear();
   Console.BackgroundColor = ConsoleColor.Blue;
   Console.ForegroundColor = ConsoleColor.Red;

   //Then everything else.
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.