Click here to Skip to main content
15,899,475 members
Please Sign up or sign in to vote.
1.67/5 (3 votes)
See more:
I got this code to change the color of the text in console application
Can you explain how is working(line by line)...

C#
[DllImport("kernel32.dll")]
       public static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput,int wAttributes);
       [DllImport("kernel32.dll")]
        public static extern IntPtr GetStdHandle(uint nStdHandle);
         uint STD_OUTPUT_HANDLE = 0xfffffff5;
           IntPtr hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

          
               SetConsoleTextAttribute(hConsole,3);
//making different color
Posted
Updated 17-Apr-12 5:34am
v2
Comments
Sergey Alexandrovich Kryukov 17-Apr-12 11:58am    
You certainly did not try hard. It was simple to achieve, importantly -- without P/Invoke...
--SA

No need to call kernel API. Simply set the desired color to Console.ForegroundColor property.
 
Share this answer
 
Comments
VJ Reddy 23-Apr-12 19:26pm    
Good answer. 5!
Wonde Tadesse 24-Apr-12 19:35pm    
Thanks
First of all, you absolutely don't need to use P/Invoke. It would kill platform compatibility. You can run the multi-colored console code which would run on many different platforms, such as Linux, Max OS X (for example, via Mono) — without recompilation. Usually, you can use 16 colors for both font background and foreground at the same time.

This article explains how. I tried it — it works. Please see:
http://www.dotnetperls.com/console-color[^].

—SA
 
Share this answer
 
Comments
Wonde Tadesse 17-Apr-12 12:30pm    
5+
Sergey Alexandrovich Kryukov 17-Apr-12 12:53pm    
Thank you, Wonde.
--SA
VJ Reddy 17-Apr-12 12:37pm    
Good advice and reference. +5
Sergey Alexandrovich Kryukov 17-Apr-12 12:53pm    
Thank you, VJ.
--SA
Shahin Khorshidnia 17-Apr-12 14:27pm    
Perfect, as always. (+5)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900