www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Windows console

reply "David B. Held" <dheld codelogicconsulting.com> writes:
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit

Some of you may have noticed that Micro$oft gimped the console in W2K 
and later, even while adding features.  In particular, it used to be 
possible to load ANSI.SYS and get nice color output in the same way you 
do on *nix terminals (via ANSI escape sequences).  Unfortunately, 
cmd.exe (and command.com) only support ansi.sys functionality in virtual 
DOS mode sessions, which basically means it only works for 16-bit DOS apps.

I happen to like color on my console, so I hacked up this little module 
to enable color escape sequences on a Win32 console (on non-win32, it 
just passes thru to writefln, because most non-Windows consoles 
correctly handle ANSI escape sequences already; but it's trivial to add 
another OS version).  It provides some SetColor() functions (if you just 
want to play with color without messing with ANSI sequences) as well as 
a WriteLine() function.  In the grand tradition of terminal emulators, 
it silently fails if you give it a bogus sequence.  This is usually the 
desired behavior anyway.

None of the other ANSI escape sequences besides setting foreground and 
background color are supported, but it would be easy for someone to add 
them.  Note that the Console is stateful, while at the same time a 
singleton.  This is necessary to properly emulate the ANSI standard.  No 
attempt is made to make it thread-safe, but I can't imagine any real 
problems in a multi-threaded environment (except that multiple 
unsynchronized threads writing to the console might mix up their colors, 
which is pretty much what you should expect with unsynchronized output, 
IMO).

The unittest should sufficiently illustrate usage.  Enjoy!

Dave
May 20 2007
parent "David B. Held" <dheld codelogicconsulting.com> writes:
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit

Here's a better version that properly flushes stdout after changing the 
color, as well as providing both Write() and WriteLine() methods.

Dave
May 20 2007