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?
This can help you:
If you want to use it in an
if, you can try this: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 containtrueif a key was pressed, otherwisefalse.