3

I have a class that accepts input via a TextReader and will allow the class to receive input from either the console or from a text box.

The following is a very basic example of what I'm trying to do:

using System.IO;

class TestReader()
{
    public TextReader CurrentStream { get; }

    public void SetInputStream( TextReader reader)
    {
        Reader = reader;
    }
}

class Program
{
    static void Main( string[] args )
    {
        TestReader rdr = new TestReader();
        rdr.SetInputStream(Console.In);

        var input = (char)rdr.CurrentStream.Read();

        Console.WriteLine( "You selected: " + input );

    }
}

How do I change the above to implement ReadKey() as the Read() method in the above example keeps accepting input until the Enter key has been pressed? I'd like to implement ReadKey() so that it only accepts a single keypress.

Thanks.

** EDIT **

To clarify things further, I am looking to implement ReadKey() without using Console.ReadKey(). I am not sure it's even possible since Google is turning up nothing so far.

Intrepid
  • 2,781
  • 2
  • 29
  • 54
  • You can't because the text reader is a stream of characters, but a key (or key combination) may not be a character. – Darren Kopp Aug 15 '13 at 16:19
  • @DarrenKopp: In that case how does `ReadKey()` do it then? It's now looking likely that I am going to have to implement my own `ReadKey()` method without using Console.ReadKey(). – Intrepid Aug 15 '13 at 16:22
  • ReadKey works because it is intercepting the keyboard key press events. – Darren Kopp Aug 15 '13 at 16:31

1 Answers1

0

i used

     ConsoleKeyInfo info;
     do
     {
        info = Console.ReadKey();
     } while (info.KeyChar != '\n' &&
        info.KeyChar != '\r'); 

to loop until i get an enter press

if you have only input stream or textBox you can just do an if statement. in case of console use my example, in case of textBox read it's text

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
  • That code won't do because you're referencing the `Console` class in your example. I don't want the class to know anything about the `Console` or `TextBox` implementations as these should be provided by the calling application, whether it'll be a Console or Winforms application. – Intrepid Aug 15 '13 at 14:01
  • @MikeClarke textBox can send it's text and Console can use the code i gave you and send the text it got, so why not do SetInputStream to receive string? – No Idea For Name Aug 15 '13 at 14:06
  • The problem is that the `TextReader` class doesn't implement a `ReadKey()` method, and in your example you're using the `Console` class directly, which won't work in a Winforms application. – Intrepid Aug 15 '13 at 14:12