From ca0445bd87014b7de68a1be9161370a556ccd0a4 Mon Sep 17 00:00:00 2001 From: tmont Date: Sun, 12 Apr 2009 07:47:42 +0000 Subject: [PATCH] reset the console colors after writing to the console (shamelessly stolen from log4net) --- .../LogHandlers/ConsoleWindowLogHandler.cs | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/SimpleLog/LogHandlers/ConsoleWindowLogHandler.cs b/SimpleLog/LogHandlers/ConsoleWindowLogHandler.cs index 907e3fa..988d4c9 100644 --- a/SimpleLog/LogHandlers/ConsoleWindowLogHandler.cs +++ b/SimpleLog/LogHandlers/ConsoleWindowLogHandler.cs @@ -19,6 +19,8 @@ namespace SimpleLog.LogHandlers { HighIntensity = 0x0008, } + + /// /// Log handler for writing log messages to a console window (e.g. cmd.exe). /// @@ -100,15 +102,50 @@ namespace SimpleLog.LogHandlers { System.IO.TextWriter writer = this.GetOutputStream(streamType); IntPtr consoleHandle = GetConsoleHandle(streamType); + //get the original colors of the console + CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo); + + ushort colorInfo = (ushort)this.GetConsoleColors(level); + + //set the console colors ConsoleWindowLogHandler.SetConsoleTextAttribute(consoleHandle, colorInfo); + //write the message to the console writer.Write(message); + + //reset the console colors + ConsoleWindowLogHandler.SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes); + return true; } #endregion - #region Win32 DLL imports + #region Win32 API stuff + [StructLayout(LayoutKind.Sequential)] + private struct COORD { + public UInt16 x; + public UInt16 y; + } + + [StructLayout(LayoutKind.Sequential)] + private struct SMALL_RECT { + public UInt16 Left; + public UInt16 Top; + public UInt16 Right; + public UInt16 Bottom; + } + + [StructLayout(LayoutKind.Sequential)] + private struct CONSOLE_SCREEN_BUFFER_INFO { + public COORD dwSize; + public COORD dwCursorPosition; + public ushort wAttributes; + public SMALL_RECT srWindow; + public COORD dwMaximumWindowSize; + } + /// /// Allocates a console window /// @@ -129,6 +166,14 @@ namespace SimpleLog.LogHandlers { /// Bitwise pairing of ConsoleColors [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern bool SetConsoleTextAttribute(IntPtr consoleHandle, ushort attributes); + + /// + /// Gets info about the console window screen + /// + /// A console handle return by GetStdHandle() + /// + [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern bool GetConsoleScreenBufferInfo(IntPtr consoleHandle, out CONSOLE_SCREEN_BUFFER_INFO bufferInfo); #endregion }