可能重复:
how to handle key press event in console application检测按键在控制台
一个简单的问题。
我正在写一个简单的基于文本的冒险游戏的乐趣,我卡在第一部分已经!如何使我的控制台检查按键I.E:按Enter键继续!
可能重复:
how to handle key press event in console application检测按键在控制台
一个简单的问题。
我正在写一个简单的基于文本的冒险游戏的乐趣,我卡在第一部分已经!如何使我的控制台检查按键I.E:按Enter键继续!
您可以使用
Console.ReadKey();
阅读1个键。那么你可以做这样的事情:
string key = Console.ReadKey().Key.ToString();
if(key.ToUpper() == "W")
Console.WriteLine("User typed 'W'!");
else
Console.WriteLine("User did not type 'W'");
或者:
if(key == "")
Console.WriteLine("User pressed enter!");
else
Console.WriteLine("User did not press enter.");
如果你如果用户键入任何东西,但印刷机后进入不在乎,你可能只是做:
// Some code here
Console.ReadLine();
// Code here will be run after they press enter
如果用户按下空格键? – Steve 2012-07-18 22:31:01
我编辑了帖子。谢谢。 – 3aw5TZetdf 2012-07-19 06:13:49
Console.Write("Press Enter to continue!")
Console.ReadLine();
直到用户点击Enter,程序才会继续。
您也可以使用Console.ReadKey
检查其他特定键:
void WaitForKey(ConsoleKey key)
{
while (Console.ReadKey(true).Key != key)
{ }
}
用法:
Console.Write("Press 'Y' to continue.");
WaitForKey(ConsoleKey.Y);
如果我错了,请纠正我,但是无论输入什么内容,这都不会让它继续吗? – 2012-07-18 21:53:56
@NortonTaylor这会很奇怪,说*按回车继续!* – user845279 2012-07-18 21:55:26
@NortonTaylor:你说得对,它将允许用户继续,无论输入什么*文本*;但直到用户实际按下Enter键后才会继续。无论如何,我已经添加了一个等待任意密钥的方法示例。 – 2012-07-18 21:58:22
的Console class包含读取和写入到 '控制台'
所需的所有方法例如
Console.Write("Press Enter to continue!")
do
{
ConsoleKeyInfo c = Console.ReadKey();
} while (c.Key != ConsoleKey.Enter);
非常感谢你! – 2012-07-18 21:56:15
一个事件,这将做到这一点。
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
Console.Write("Press Enter to continue!")
}
}
OP说这是一个控制台应用程序...编辑:没关系..你做了鬼祟的忍者编辑! – 2012-07-18 21:58:12
然后在那种情况下,'Console.ReadKey()'可能是最好的选择。 – 2012-07-18 22:00:23
可能重复:http://stackoverflow.com/q/8898182/946904 – 2012-07-18 21:57:17
技术上讲,它不是,我其实并没有要求要显示的关键。 – 2012-07-18 21:58:35
你是对的,它不是一个确切的重复,但如果你在这里比较答案和答案,你会看到他们非常相似。 – 2012-07-18 22:03:33