Reputation: 1783
In my program I work with an input stream and an output stream. These can in pricipal be any kind of streams, but in most cases they are simply the standard input and output in the console. Here is how the streams are initialized:
StreamReader input = null;
StreamWriter output = null;
/* ... */
if (output == null)
{
output = new StreamWriter(Console.OpenStandardOutput());
}
if (input == null)
{
input = new StreamReader(Console.OpenStandardInput());
}
My problem is that the input from the console is always written to the console. I have some special characters that I do not want written to the console. To be more specific I want to use tab to autocomplete for instance.
When googling around the only solution that I found was to use Console.ReadKey(). However, this would ruin my support for streams in general, since streams does not have a similar method.
My question comes down to: Is there any way detach the input stream from the output stream? Alternative ways to solve this are welcome as well.
Upvotes: 0
Views: 338
Reputation: 4777
The Console class is a strange beast. You are going to need Console.ReadKey() to do what you want. One problem is that without it you won't get any input from your stream until the users presses the enter key. Here's a really simple example:
char inp;
do {
var x = Console.ReadKey(true);
inp = x.KeyChar;
output.Write(inp);
if (x.Key == ConsoleKey.Enter) { Console.WriteLine(); }
} while (inp != 'x');
If you want to stick with a stream paradigm you can do something like this:
public class ConsoleStream: StreamReader {
public ConsoleStream(): base(new MemoryStream()) {}
public override int Read() {
var key = Console.ReadKey(true);
return (int) key.KeyChar;
}
}
The MemoryStream above is not used, it just there to allow the base StreamReader to be constructed. You use the class like this:
var cin = new ConsoleStream();
char inp;
do {
inp = (char) cin.Read();
Console.Write(inp);
if (inp == '\r') { Console.WriteLine(); }
} while (inp != 'x');
If it were me I'd just use ReadKey directly.
Upvotes: 1