Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if any key pressed in console application C#

I need to check if any key is pressed in a console application. The key can be any key in the keyboard. Something like:

if(keypressed)
{ 

//Cleanup the resources used

}

I had come up with this:

ConsoleKeyInfo cki;
cki=Console.ReadKey();

if(cki.Equals(cki))
Console.WriteLine("key pressed");

It works well with all keys except modifier keys - how can I check these keys?

like image 265
user1502952 Avatar asked Jul 25 '12 10:07

user1502952


People also ask

What is the use of console ReadKey ()?

ReadKey() Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window.

What is ConsoleKeyInfo?

The ConsoleKeyInfo object describes the ConsoleKey constant and Unicode character, if any, that correspond to the pressed console key.

What is the difference between ReadLine and ReadKey in C#?

Difference between ReadLine(), Read(), ReadKey() in C# As MSDN is actually pretty clear. Reads the next line of characters from the standard input stream. simply you can say, it read all the characters from user input. (and finish when press enter).

How do I stop the console from closing in C#?

The first solution is to run the application without debugging by using Ctrl+F5 instead of just F5. The console window will remain open when the program has finished. The disadvantage of this is that you lose Visual Studio's debug information.


2 Answers

This can help you:

Console.WriteLine("Press any key to stop");
do {
    while (! Console.KeyAvailable) {
        // Do something
   }       
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);

If you want to use it in an if, you can try this:

ConsoleKeyInfo cki;
while (true)
{
   cki = Console.ReadKey();
   if (cki.Key == ConsoleKey.Escape)
     break;
}

For any key is very simple: remove the if.


As @DawidFerenczy mentioned we have to note that Console.ReadKey() is blocking. It stops the execution and waits until a key is pressed. Depending on the context, this may (not) be handy.

If you need to not block the execution, just test Console.KeyAvailable. It will contain true if a key was pressed, otherwise false.

like image 119
Ionică Bizău Avatar answered Sep 17 '22 05:09

Ionică Bizău


Have a look at the Console.KeyAvailible if you want nonblocking.

do {
    Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");

// Your code could perform some useful task in the following loop. However, 
// for the sake of this example we'll merely pause for a quarter second.

    while (Console.KeyAvailable == false)
        Thread.Sleep(250); // Loop until input is entered.
    cki = Console.ReadKey(true);
    Console.WriteLine("You pressed the '{0}' key.", cki.Key);
    } while(cki.Key != ConsoleKey.X);
}

If you want blocking then use Console.ReadKey.

like image 26
John Mitchell Avatar answered Sep 18 '22 05:09

John Mitchell