Checking if any key is pressed in C # console application

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

if(keypressed) { //Cleanup the resources used } 

I came 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?

+7
source share
2 answers

This may 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 if , you can try the following:

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

For any key is very simple: remove if .


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

If you don't need to block execution, just check out Console.KeyAvailable . It will contain true if the key is pressed, otherwise false .

+12
source

See Console.KeyAvailible if you want to non-block.

 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 to block, use Console.ReadKey .

+5
source

All Articles