Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to use Text Color Windows API function for Consol Application in C#

1 Answer

0 votes
using System;
using System.Runtime.InteropServices;

namespace API
{
	class Class1
	{
		[DllImport("User32.dll")] 
		private extern static IntPtr GetWindowDC( IntPtr hWnd ); 

		[DllImport("gdi32")] public static extern int SetBkColor(int hDC, int crColor);

		static void Main(string[] args)
		{
			Class1 c = new Class1();
			c.change();

            IntPtr hOut = GetStdHandle(-11); // -11 is the standard output device

			IntPtr hDC = GetWindowDC(hOut ); 

            SetBkColor( (int)hDC, 256 ); 
		}

		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, 
                                                          CharacterAttributes wAttributes);
		[DllImport("kernel32.dll")]
		public static extern IntPtr GetStdHandle(int nStdHandle); 

		void change()
		{
			IntPtr hOut;
            hOut = GetStdHandle(-11); // -11 is the standard output device
			SetConsoleTextAttribute(hOut, CharacterAttributes.FOREGROUND_BLUE );
			Console.WriteLine(" Hello Blue World ");
			SetConsoleTextAttribute(hOut, CharacterAttributes.BACKGROUND_RED);
			Console.WriteLine(" C# Programmer ");
			SetConsoleTextAttribute(hOut, CharacterAttributes.BACKGROUND_GREEN );
			Console.WriteLine(" A Text Line  ");
			SetConsoleTextAttribute(hOut, CharacterAttributes.FOREGROUND_RED | 
                                          CharacterAttributes.FOREGROUND_GREEN | 
                                          CharacterAttributes.FOREGROUND_INTENSITY);
			
			Console.WriteLine(" Yellow Me? ");
		}

		public enum CharacterAttributes
		{
			FOREGROUND_BLUE = 0x0001,
			FOREGROUND_GREEN = 0x0002,
			FOREGROUND_RED = 0x0004,
			FOREGROUND_INTENSITY = 0x0008,
			BACKGROUND_BLUE = 0x0010,
			BACKGROUND_GREEN = 0x0020,
			BACKGROUND_RED = 0x0040,
			BACKGROUND_INTENSITY = 0x0080,
			COMMON_LVB_LEADING_BYTE = 0x0100,
			COMMON_LVB_TRAILING_BYTE = 0x0200,
			COMMON_LVB_GRID_HORIZONTAL = 0x0400,
			COMMON_LVB_GRID_LVERTICAL = 0x0800,
			COMMON_LVB_GRID_RVERTICAL = 0x1000,
			COMMON_LVB_REVERSE_VIDEO = 0x4000,
			COMMON_LVB_UNDERSCORE = 0x8000
		}
	}
}



answered Aug 11, 2014 by avibootz
edited Aug 12, 2014 by avibootz

Related questions

1 answer 2,448 views
1 answer 329 views
1 answer 243 views
1 answer 233 views
1 answer 183 views
...