C# 检测控制台中的按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11550879/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:15:05  来源:igfitidea点击:

Detecting key presses in console

c#

提问by Hello World

Possible Duplicate:
how to handle key press event in console application

可能的重复:
如何处理控制台应用程序中的按键事件

a simple question.

一个简单的问题。

I am writing a simple text based adventure game for fun and I am stuck on the first part already! How can I make my console check for key presses I.E: press enter to continue!

我正在写一个简单的基于文本的冒险游戏来玩,但我已经被困在第一部分了!如何让我的控制台检查按键 IE:按 Enter 继续!

采纳答案by matthewr

You can use

您可以使用

Console.ReadKey();

To read 1 key. You could then do something like this:

读取1个键。然后你可以做这样的事情:

string key = Console.ReadKey().Key.ToString();
if(key.ToUpper() == "W")
    Console.WriteLine("User typed 'W'!");
else 
    Console.WriteLine("User did not type 'W'");

Or:

或者:

if(key == "")
    Console.WriteLine("User pressed enter!");
else
    Console.WriteLine("User did not press enter.");

And if you do not care if the user types anything but presses enter after, you could just do:

如果您不关心用户是否输入任何内容但按 Enter 键,您可以这样做:

// Some code here
Console.ReadLine();
// Code here will be run after they press enter

回答by Dan Tao

Console.Write("Press Enter to continue!")
Console.ReadLine();

The program will not continue until the user hits Enter.

在用户按 Enter 之前,程序不会继续。

You can also check for other specific keys using Console.ReadKey:

您还可以使用Console.ReadKey以下命令检查其他特定键:

void WaitForKey(ConsoleKey key)
{
    while (Console.ReadKey(true).Key != key)
    { }
}

Usage:

用法:

Console.Write("Press 'Y' to continue.");
WaitForKey(ConsoleKey.Y);

回答by Steve

The Console classcontains all the methods needed to read and write to the 'console'

控制台类包括读取和写入到“控制台”所需的所有方法

For example

例如

Console.Write("Press Enter to continue!")  
do
{
    ConsoleKeyInfo c = Console.ReadKey();
} while (c.Key != ConsoleKey.Enter);

回答by DROP TABLE users

An event, that would do it.

一个事件,那就可以了。

private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
        if (e.Key == Key.Return)
        {
            Console.Write("Press Enter to continue!")
        }
 }