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

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

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

我想知道,我应该input什么,所以我可以打电话给那个事件?

对于控制台应用程序,您可以执行此操作, 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挂钩

不幸的是,Console类没有为用户input定义任何事件,但是如果你想输出被按下的当前字符,你可以执行以下操作:

  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对象,它封装了许多关于被按下的键的信息。