Sunday 15 May 2011

c# - How to change text colour in console application after its printed? -



c# - How to change text colour in console application after its printed? -

i know question far-fetched, if feature possible, awesome. want alter colour of text player writing it, if keywords typed, alter colour.

i know can alter cursor location, don't know if helpful in changing colour. know can console.clear, if possible not that, since have save string , re-write all, , not applicable/plausible program.

short answer: no, because standard-output has historically been write-only medium (think 1960s teleprinters).

complicated answer: yes, magic of \r.

basically, you'd read user types on per-keystroke basis , maintain track of (perhaps in stringbuilder), if user types in magic-word erase printed line using \r (which moves caret first column of console without creating new line) , over-write printed there, setting console.foregroundcolor before re-printing it.

you don't need manually print each keystroke (until reprinting highlight) console.readkey not interfere otherwise normal operation of console window , local-echo behaviour.,

here's simple:

stringbuilder sb = new stringbuilder(); while( true ) { consolekeyinfo key = console.readkey(); if( !char.iscontrol( key.keychar ) ) { sb.append( key.keychar ); if( sb.tostring() == "magic!" ) { console.write("\r"); console.foregroundcolor = consolecolor.blue; console.write( sb.tostring() ); console.resetcolor(); } } else { sb.length = 0; } }

this code buggy , incomplete, think demonstrates underlying concept.

c# console-application

No comments:

Post a Comment