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

R.V*_*tor 26 c# event-handling keyboard-events keylogger

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

    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);
    }
Run Code Online (Sandbox Code Playgroud)

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

par*_*mar 22

对于控制台应用程序,您可以执行此操作,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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这仅在您的控制台应用程序具有焦点时才有效.如果要收集系统范围的按键事件,可以使用Windows挂钩


Jam*_*ler 14

遗憾的是,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);
     }
 }
Run Code Online (Sandbox Code Playgroud)

Console.ReadKey返回一个ConsoleKeyInfo对象,该对象封装了有关按下的键的大量信息.