How to handle key press event in console application
Solution 1:
For console application you can do this, the do while
loop runs untill you press x
public class Program
{
public static void Main()
{
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
Console.WriteLine(keyinfo.Key + " was pressed");
}
while (keyinfo.Key != ConsoleKey.X);
}
}
This will only work if your console application has focus. If you want to gather system wide key press events you can use windows hooks
Solution 2:
Unfortunately the Console class does not have any events defined for user input, however if you wish to output the current character which was pressed, you can do the following:
static void Main(string[] args)
{
//This will loop indefinitely
while (true)
{
/*Output the character which was pressed. This will duplicate the input, such
that if you press 'a' the output will be 'aa'. To prevent this, pass true to
the ReadKey overload*/
Console.Write(Console.ReadKey().KeyChar);
}
}
Console.ReadKey returns a ConsoleKeyInfo object, which encapsulates a lot of information about the key which was pressed.