如何在控制台应用程序中处理按键事件

32

我想创建一个控制台应用程序,它可以在控制台屏幕上显示按下的键,我目前编写了以下代码:

    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);
    }

我想知道,在主函数中应该输入什么,以便我可以调用那个事件?

3个回答

32

对于控制台应用程序,你可以这样做,do while 循环会一直运行,直到你按下 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);
    }
}

只有当你的控制台应用程序拥有焦点时,这将起作用。如果你想要收集整个系统的按键事件,你可以使用Windows钩子


15

很遗憾,Console类没有为用户输入定义任何事件,但是如果您希望输出当前按下的字符,可以执行以下操作:

 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 返回一个 ConsoleKeyInfo 对象,该对象封装了按下的键的大量信息。


2

另一种解决方案,我用它来制作我的基于文本的冒险游戏。

        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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接