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

问题描述 投票:0回答:3

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

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

我想知道,我应该在 main 中输入什么以便调用该事件?

c# event-handling keyboard-events keylogger
3个回答
33
投票

对于控制台应用程序,您可以执行此操作,

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 hooks


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 对象,该对象封装了有关按下的按键的大量信息。


3
投票

另一个解决方案,我将其用于基于文本的冒险。

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);
© www.soinside.com 2019 - 2024. All rights reserved.