Section 2: custom text display color the text preset displayed on the console is black and white, although you can use the color command to change the background color and foreground color of the entire console, however, what we study here is that in the same Console window, the program can input texts of different colors according to different requirements. A colorful Console window will be very attractive to users. if the text in the console is not set to color, you need to call the system API setconsoletextattribute function. The following code is available on the Internet. I have tested it and I will post it for your reference: // lelecolour. CS
Using system;
// Need this to make API CILS
Using system. runtime. interopservices;
Using pfitzsimons. consolecolour;
Namespace pfitzsimons. consolecolour
...{
/** // <Summary>
/// Static class for console color manipulation.
/// </Summary>
Public class lelecolour
...{
// Constants for console streams
Const int std_input_handle =-10;
Const int std_output_handle =-11;
Const int std_error_handle =-12;
[Dllimportattribute ("kernel32.dll")]
Private Static extern intptr getstdhandle
(
Int nstdhandle // input, output, or error device
);
[Dllimportattribute ("kernel32.dll")]
Private Static extern bool setconsoletextattribute
(
Intptr hconsoleoutput, // handle to screen Buffer
Int wattributes // text and background colors
);
// Colours that can be set
[Flags]
Public Enum foregroundcolour
...{
Black = 0x0000,
Blue = 0x0001,
Green = 0x0002,
Cyan = 0x0003,
Red = 0x0004,
Magenta = 0x0005,
Yellow = 0x0006,
Grey = 0x0007,
White = 0x0008
}
// Class can not be created, so we can set colours
// Without a variable
Private consolecolour ()
...{
}
Public static bool setforegroundcolour ()
...{
// Default to a white-gray
Return setforegroundcolour (foregroundcolour. grey );
}
Public static bool setforegroundcolour (
Foregroundcolour)
...{
// Default to a bright white-gray
Return setforegroundcolour (foregroundcolour, true );
}
Public static bool setforegroundcolour (
Foregroundcolour,
Bool brightcolours)
...{
// Get the current console handle
Intptr nconsole = getstdhandle (std_output_handle );
Int colourmap;
// If we want bright colours or it with white
If (brightcolours)
Colourmap = (INT) foregroundcolour |
(INT) foregroundcolour. White;
Else
Colourmap = (INT) foregroundcolour;
// Call the API and return the result
Return setconsoletextattribute (nconsole, colourmap );
}
}
}
// Then the main program
Namespace MyApp
...{
Public class MyApp
...{
Public static void main ()
...{
Consolecolour. setforegroundcolour (
Consolecolour. foregroundcolour. Green );
Console. writeline ("text in green ");
Consolecolour. setforegroundcolour (
Lelecolour. foregroundcolour. Red );
Console. writeline ("text in red ");
// Reset console back to a default
Lelecolour. setforegroundcolour ();
Console. writeline ("text in default ");
}
}
}