using System; using System.Runtime.InteropServices; /// /// Provide some Kernel32 functions for the Console /// class ConsoleMode { // Some constants brought over from WinCon.h // constants for console streams const int STD_INPUT_HANDLE = -10; const int STD_OUTPUT_HANDLE = -11; const int STD_ERROR_HANDLE = -12; // // Input Mode flags: // const uint ENABLE_PROCESSED_INPUT = 1; const uint ENABLE_LINE_INPUT = 2; const uint ENABLE_ECHO_INPUT = 4; const uint ENABLE_WINDOW_INPUT = 8; const uint ENABLE_MOUSE_INPUT = 10; // // Output Mode flags: // const uint ENABLE_PROCESSED_OUTPUT = 1; const uint ENABLE_WRAP_AT_EOL_OUTPUT = 2; // // DLL imports // [DllImportAttribute("Kernel32.Dll")] private static extern IntPtr GetStdHandle( int nStdHandle ); [DllImportAttribute("Kernel32.Dll")] private static extern bool SetConsoleMode( IntPtr hConsoleHandle, uint dwMode ); [DllImportAttribute("Kernel32.Dll")] private static extern bool GetConsoleMode( IntPtr hConsoleHandle, out uint lpMode ); private ConsoleMode() { } public static void SetSilentMode( bool turnOn ) { IntPtr nConsole = GetStdHandle( STD_INPUT_HANDLE ); uint lpMode, newMode; GetConsoleMode( nConsole, out lpMode ); if (turnOn) { newMode = lpMode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT); } else { newMode = lpMode & (ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT); } if (!SetConsoleMode(nConsole, newMode)) { throw new ApplicationException("SetConsoleMode failed"); } } // --------- Colors ------------ [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 ForeGroundColor { Black = 0x0000, Blue = 0x0001, Green = 0x0002, Cyan = 0x0003, Red = 0x0004, Magenta = 0x0005, Yellow = 0x0006, Grey = 0x0007, White = 0x0008 } public static bool SetForeGroundColor() { // default to a white-grey return SetForeGroundColor(ForeGroundColor.Grey); } public static bool SetForeGroundColor( ForeGroundColor foreGroundColor) { // default to a bright white-grey return SetForeGroundColor(foreGroundColor, true); } public static bool SetForeGroundColor(ForeGroundColor foreGroundColor, bool brightColors) { // get the current console handle IntPtr nConsole = GetStdHandle(STD_OUTPUT_HANDLE); int colourMap; // if we want bright colours OR it with white if (brightColors) colourMap = (int) foreGroundColor | (int) ForeGroundColor.White; else colourMap = (int) foreGroundColor; // call the api and return the result return SetConsoleTextAttribute(nConsole, colourMap); } }