Important alert: (current site time 10/31/2014 3:16:05 AM EDT)
 

VB icon

Coloring the Console Application (AddingText and Background color in C#)

Email
Submitted on: 12/9/2004 6:11:06 AM
By: SolutionNet 
Level: Intermediate
User Rating: By 2 Users
Compatibility: C#
Views: 8074
author picture
(About the author)
 
     This code changes text and back ground color in a console C# Application. This artical also explain that how we can call Win32 Api's in our c# program or say how to use unmanaged code in managed enviroment.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
//**************************************
// Name: Coloring the Console Application (AddingText and Background color in C#)
// Description:This code changes text and back ground color in a console C# Application. This artical also explain that how we can call Win32 Api's in our c# program or say how to use unmanaged code in managed enviroment.
// By: SolutionNet
//
//This code is copyrighted and has// limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=3055&lngWId=10//for details.//**************************************

Coloring the console
Kashif Bilal
	
When working with console applications in c#, always a black screen with white foreground comes. We can change the fore color as well as back ground color of our console application by using win32 API SetConsoleTextAttribute().
SetConsoleTextAttribute takes two arguments 
1.	Handle to console screen buffer
2.	character attributes
BOOL SetConsoleTextAttribute(
 HANDLE hConsoleOutput,
 WORD wAttributes
);
We can get handle to console screen buffer by using another function of win32 API i.e. GetStdHandle(),which takes a parameter and returns handle for input, output or error device.
We give -10 for input,-11 for output and -12 for error device as parameter to GetStdHandle function.
We have attributes for fore ground and background colors like 0x0001 for fore ground blue and 0x0010 for back ground blue.
How Use Win32 API Function in C#.
First of all declare the function using DllImport attribute. An API function must be declared static extern.
DllImport is used to call an unmanaged code inside a mangaed code, so we must have to use it to call unmanaged win32 APIís.
Letís start an example
using System;
using System.Runtime.InteropServices; // for DllImport attribute 
namespace color_console
{
	
	class Class1
	{
		
		
		static void Main(string[] args)
		{
			//
			// TODO: Add code to start application here
			//
			Class1 c =new Class1();
			c.change();
		}
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool SetConsoleTextAttribute(
			IntPtr hConsoleOutput,
			CharacterAttributes wAttributes); /* declaring the setconsoletextattribute function*/
		[DllImport("kernel32.dll")]
		public static extern IntPtr GetStdHandle(int nStdHandle); //declaring the getstdhandle funtion 
																/* to get thehandle that would be used in setConsoletextattribute function */
		void change()
		{
			IntPtr hOut; /* declaring varianle to get handle*/
			hOut= GetStdHandle(-11);/* -11 is sent for output device*/ 
			
		
			/*Displaying text in different colors and background colors*/
				SetConsoleTextAttribute(hOut, CharacterAttributes.FOREGROUND_BLUE );
				Console.WriteLine(" Subhan ALLAH ");
				SetConsoleTextAttribute(hOut, CharacterAttributes.BACKGROUND_RED);
				Console.WriteLine(" Alkhamdolillah ");
				SetConsoleTextAttribute(hOut, CharacterAttributes.BACKGROUND_GREEN );
						Console.WriteLine(" Allah O Akbar ");
				SetConsoleTextAttribute(hOut, CharacterAttributes.FOREGROUND_RED );
				Console.WriteLine(" Pakistan ");
			
		}
/* This enumeration lists all of the character attributes. You can combine attributes to achieve specific effects.*/
		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
		}
	}
}
We can also change the font and cursor of console application using win32 APIís.
Changing the Title of Console is also much easier, just use SetConsoleTitle()function and provide a string to it as parameter, that would be title of console. You can do it easily
[DllImport("kernel32.dll")
		public static extern bool SetConsoleTitle(String lpConsoleTitle);
First declare setconsoletitle function and then use it
SetConsoleTitle(" ALlah O Akbar ... ");
Thanks Ö 
Kashif Bilal
kashiff@gmail.com


Other 1 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

12/9/2009 1:27:38 AMAl

You can also use the built-in Console.BackgroundColor, Console.ForegroundColor and the ConsoleColor enumeration
(If this comment was disrespectful, please report it.)

 
12/9/2009 5:17:44 PMDerek Schwartz

This must be for .NET v1.1, since .NET 2.0+ has the atributes Console.BackgroundColor,
Console.ForegroundColor with a color definition from System.ConsoleColor.

This also appears to be a copy/paste example from "http://www.c-sharpcorner.com/UploadFile/kashifbilal/ColoringTheConsole12192005015120AM/ ColoringTheConsole.aspx"
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.