-4

I want to break or pause a do/while loop if a user presses a key in the console. I have tried ReadLine or ReadKey but then my program stops and it is waiting for input, but I only want my program to stop after user input.

My code:

do
{   
    //do some code until user input
    Console.WriteLine("for settings: Press 's'");

    ConsoleKeyInfo cki;
    cki = Console.ReadKey();    // here the program stops and waits for input but I don't want it
    if (cki.Key.ToString() == "S")
    {
        Console.WriteLine("SETTINGS");
    }
} while (true);
Peter B
  • 22,460
  • 5
  • 32
  • 69
martimoto
  • 11
  • 2
  • 1
    Please read this https://stackoverflow.com/help/how-to-ask to know . Please at-least post the code to give a hint. – Dharani Kumar Jun 04 '18 at 12:34
  • 2
    It would be awesome if you could provide a [mcve] of your attempt so far. – mjwills Jun 04 '18 at 12:35
  • 3
    https://stackoverflow.com/questions/5891538/listen-for-key-press-in-net-console-app is likely the link you want to read. – mjwills Jun 04 '18 at 12:37
  • @A.Godnov: The problem is pretty clear, and the comment you posted is not only irrelevant to the problem but is also rather rude. And we use real words here, not txtspeak. You're not texting your friends. Use real words here. – Ken White Jun 04 '18 at 12:39

2 Answers2

0

Check out Console.KeyAvailable this will be true when a user presses a key. When it is true then you can do Console.ReadKey()

Stewart Parry
  • 128
  • 3
  • 8
-2

You won't be able to have your program do that easily, that is actually doing 2 things at once 1) waiting on input (what readline/readkey does) and 2) continuing the work at the same time.

You could do this with multithreading by launching having your logic executing on one threat and the waiting on user input on another thread, then communicating between threads when user input happens but based on your question this is probably a too compelx answer, i will gladly write a sample but i think it is more likely to confuse than to help.

Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78
  • This information is incorrect. https://stackoverflow.com/questions/5891538/listen-for-key-press-in-net-console-app – Ken White Jun 04 '18 at 12:40
  • Thank you, that works for me. I've done it like this: `do { Console.WriteLine("for settings: Press 's'"); ... UserInputThread.Start(); } while(true); public static void UserInput() { ConsoleKeyInfo cki; cki = Console.ReadKey(); if (cki.Key.ToString() == "S") { ...} }` – martimoto Jun 04 '18 at 13:07
  • @KenWhite i agree if you read his question literally and focus on key instead of string but since he mentioned ReadKey AND ReadLine i thought he may need both – Ronan Thibaudau Jun 04 '18 at 16:15