C# 如何处理控制台应用程序中的按键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8898182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle key press event in console application
提问by R.Vector
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?
我想知道,我应该在 main 中输入什么才能调用该事件?
采纳答案by parapura rajkumar
For console application you can do this, the do whileloop runs untill you press x
对于控制台应用程序,您可以执行此操作,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);
}
}
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
这仅在您的控制台应用程序具有焦点时才有效。如果你想收集系统范围内的按键事件,你可以使用windows hooks
回答by James Shuttler
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:
不幸的是 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.ReadKeyreturns a ConsoleKeyInfoobject, which encapsulates a lot of information about the key which was pressed.
Console.ReadKey返回一个ConsoleKeyInfo对象,该对象封装了大量有关按下的键的信息。
回答by Daniel Kubicek
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);

