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.
Solution 3
Another solution, I used it for my text based adventure.
ConsoleKey choice;
do
{
choice = Console.ReadKey(true).Key;
switch (choice)
{
// 1 ! key
case ConsoleKey.D1:
Console.WriteLine("1. Choice");
break;
//2 @ key
case ConsoleKey.D2:
Console.WriteLine("2. Choice");
break;
}
} while (choice != ConsoleKey.D1 && choice != ConsoleKey.D2);
R.Vector
Hi guys , my name is ryan , i am studying computer science , i am working with C# and SQL at the moment .
Updated on January 24, 2020Comments
-
R.Vector over 4 years
I want to create a console application that will display the key that is pressed on the console screen, I made this code so far:
static void Main(string[] args) { // this is absolutely wrong, but I hope you get what I mean PreviewKeyDownEventArgs += new PreviewKeyDownEventArgs(keylogger); } private void keylogger(KeyEventArgs e) { Console.Write(e.KeyCode); }
I want to know, what should I type in main so I can call that event?