2

I am writing a text adventure in c# for a school assignment and I've already come across a problem.

I made a function to type out sentences like this:

public static void Zin (string zin)
    {

        foreach (char c in zin)
        {
            Console.Write(c);
            Thread.Sleep(50);
        }

Now this works but I want to implement that when the player hits the enter key, the sentence is typed out on the console instantly.

I'm not sure how to do this. I've tried using a while loop in the foreach loop that checks wether enter is being hit and then print out the sentence but that doesn't work.

Thanks in advance!

NineBerry
  • 26,306
  • 3
  • 62
  • 93
S. Neut
  • 43
  • 5

1 Answers1

1

You can use the Console.KeyAvailable property to find out whether keys have been pressed that have not been read via any of the Console.Read* methods.

When keys have been pressed, skip the waiting within the loop. After the loop, read all keys that have been pressed during the loop, so that they will not be returned when you use Console.Read* later on.

public static void Zin(string zin)
{
     foreach (char c in zin)
     {
          Console.Write(c);

          // Only wait when no key has been pressed
          if (!Console.KeyAvailable)
          {
               Thread.Sleep(50);
          }
     }

     // When keys have been pressed during our string output, read all of them, so they are not used for the following input
     while (Console.KeyAvailable)
     {
          Console.ReadKey(true);
     }
}

See also Listen for key press in .NET console app

Community
  • 1
  • 1
NineBerry
  • 26,306
  • 3
  • 62
  • 93
  • Thanks for your answer first of all! It does not seem to work yet however. What exactly does the Console.KeyAvailable function do? – S. Neut Oct 09 '16 at 13:51
  • What does not work? I have tested this in code. The answer contains a link to the documentation of Console.KeyAvailable. Just click on the text to go to the documentation. – NineBerry Oct 09 '16 at 13:54
  • hmm, in my code, nothing happens when I press the 'enter' key. The console just keeps on writing the sentence letter by letter – S. Neut Oct 09 '16 at 13:56
  • Have you copied the Zin() method 1 to 1 from my answer or modified something? Have you made sure the code was compiled after making the change? – NineBerry Oct 09 '16 at 13:58
  • 1
    oh wait I put the while loop in the foreach loop, that's not gonna work obviously ;) Thanks alot man! I also actually understand what you did! – S. Neut Oct 09 '16 at 14:03
  • You are welcome. Since this was your first question: Please click the checkmark besides my answer to mark it as the correct answer. We both get prestige from that. – NineBerry Oct 09 '16 at 14:09
  • Done :) just one more thing: It works for all buttons now instead of only the enter key – S. Neut Oct 09 '16 at 14:11