'C# Console application: Trap key press event without waiting for a key to be pressed [duplicate]
I am writing a console application using C#. I am unable to find a way to trap a key down (without having to wait for a key press in a loop). I want my program to run something without waiting for key press. However when any key is pressed, the event should be detected for some action
Solution 1:[1]
This was already answered here: Listen for key press in .NET console app
You can use do while while checking Console.KeyAvailable or stop application to wait for read key but do work in background thread.
Solution 2:[2]
As Ernestas mentioned above Console.KeyAvailable is likely your best bet. To implement it I would do something like this:
bool keyPressed = false;
while(!keyPressed)
{
if(Console.KeyAvailable)
keyPressed = true;
//DO STUFF WHILE WAITING FOR KEYPRESS
}
else
{
//DO STUFF YOU WANTED TO DO AFTER KEYPRESS
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ErnestasI |
| Solution 2 |
