How to handle key press event in console application

R.Vector picture R.Vector · Jan 17, 2012 · Viewed 67.3k times · Source

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?

Answer

parapura rajkumar picture parapura rajkumar · Jan 17, 2012

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