I am writing a console app and found this method to end a loop on a keypress:
while (!Console.KeyAvailable){//do stuff}
It works, but it echos the key that was pressed back to the prompt. Is there a better method?
edit:
To clarify more, the loop runs and if hit the letter j the loop ends and the program exits. However, I get the following output at the prompt:
C:\>j
If you want to exit from a loop after a particular key is pressed, then instead of Console.KeyAvailable you can use the Console.ReadKey() function and check the return type of this function as an exit condition.
Here is the implementation.
while (true) {
var keyPressed = Console.ReadKey(true);
if (keyPressed.KeyChar == 'j') break;
//do something
Console.WriteLine("Key pressed: " + keyPressed.KeyChar);
}
For more details: C# Console - hide the input from console window while typing
Related
I have been researching in how to stop a console application when pressing esc (or any key really.
I ran into this solution
Listen for key press in .NET console app
Now, I was trying to apply it to my case:
I should stop my console app, which is a loop, when I press any key.
Coming from the solution provided in the topic above, I added my own part as follows:
Console.WriteLine("Press ESC to stop");
do {
while (! Console.KeyAvailable) {
foreach (var station in WeatherStations.station)
{
var stationAirParams = station.value?.FirstOrDefault();
Console.WriteLine(
station.name + " " + (stationAirParams == null
? ""
: stationAirParams.value)
);
Thread.Sleep(100);
}
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
That said... why isn't the loop stopping?
Your approach uses polling in a single thread, and it is not event driven.
The inner loop won't stop on key press. It will simply finish its work before the code checks for key press for the first time in the outer loops.
Move an abort condition like the following
if(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)
{
break;
}
to the innermost loop.
There is another answer here which shows how to spawn a background thread to do the work whilst waiting for a keypress to exit on the main thread.
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);
Check out Console.KeyAvailable this will be true when a user presses a key. When it is true then you can do Console.ReadKey()
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.
I just wanted to ask if it was possible to make an event run if the player presses a specific button. This should be tested at every point in the console application but not if there is a Console.ReadLine() event used at the moment.
Is there a way to do this?
You can use Console.ReadKey() method like this
ConsoleKeyInfo keyInfo = Console.ReadKey();
if(keyInfo.Key == ConsoleKey.A)
{
}
For more info see https://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx
I'm trying to run a program like a for loop. But when it starts debugging the console window disappears immediately. How do I stop this. I need something like press any key to continue.
Have a statement like
Console.Read()
That way, the console will remain until you press a key.
For more information, read here.
Write Console.ReadLine() or Console.Read() or Console.ReadKey() at the end of your program.
It will make your screen wait for your key press in order to exit.
I just found out that pressing the Ctrl + F5 key makes the console stay.
You didn't mention any example code. This is my example code. Program waits for pressing a key
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
I'm working on a little part of my program, handling the input, basically I have this little code:
bool Done = false;
while (!Done)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
//Action
}
}
The main problem with this is that the code will handle the ReadKey even between actions.
So if you have a menu where you can press keys and then it would say "you pressed: x" if you press any buttons while it shows you this message, the ReadKey already gets that new key.
So I want to block any further input until the user sees the menu again.
Not so sure this make sense, personally I like it when keystrokes don't disappear and I can type ahead. But you can flush the keyboard buffer like this:
while (!Done)
{
while (Console.KeyAvailable) Console.ReadKey(true);
ConsoleKeyInfo key = Console.ReadKey(true);
// etc..
}
You can not block input,
Even if you do not process it, it goes to the keyboard buffer.
You can simply stop getting them out of the buffer though.