How to handle key press event in console applicati

2019-01-02 18:57发布

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?

3条回答
一个人的天荒地老
2楼-- · 2019-01-02 19:06

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.

查看更多
余生无你
3楼-- · 2019-01-02 19:21

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

查看更多
萌妹纸的霸气范
4楼-- · 2019-01-02 19:23

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);
查看更多
登录 后发表回答