6

我在 Visual Studio 2013 中用 C# 编写了一个简单的程序。在我的程序结束时,我指示用户:

“请按 Enter 退出程序。”

我想在下一行从键盘获取输入,如果ENTER按下,程序将退出。

谁能告诉我如何实现这个功能?

我尝试了以下代码:

Console.WriteLine("Press ENTER to close console......");
String line = Console.ReadLine();

if(line == "enter")
{
    System.Environment.Exit(0);
}
4

4 回答 4

10

尝试以下操作:

ConsoleKeyInfo keyInfo = Console.ReadKey();
while(keyInfo.Key != ConsoleKey.Enter)
    keyInfo = Console.ReadKey();

你也可以使用do-while。更多信息:Console.ReadKey()

于 2015-09-18T15:45:27.753 回答
6

像这样使用Console.ReadKey(true);

ConsoleKeyInfo keyInfo = Console.ReadKey(true); //true here mean we won't output the key to the console, just cleaner in my opinion.
if (keyInfo.Key == ConsoleKey.Enter)
{
    //Here is your enter key pressed!
}
于 2015-09-18T15:46:00.127 回答
5

如果你这样写程序:

  • 你不需要打电话System.Environment.Exit(0);
  • 你也不需要检查输入键。

例子:

class Program
{
    static void Main(string[] args)
    {
        //....
        Console.WriteLine("Press ENTER to exit...");
        Console.ReadLine();
    }
}

另一个例子:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Press Enter in an emplty line to exit...");
        var line= "";
        line = Console.ReadLine();
        while (!string.IsNullOrEmpty(line))
        {
            Console.WriteLine(string.Format("You entered: {0}, Enter next or press enter to exit...", line));
            line = Console.ReadLine();
        }
    }
}

又一个例子:

如果需要,可以检查读取的值Console.ReadLine()是否为空,然后Environment.Exit(0);

//...
var line= Console.ReadLine();
if(string.IsNullOrEmpty(line))
    Environment.Exit(0)
else
    Console.WriteLine(line);
//...
于 2015-09-18T15:43:47.390 回答
0
Console.WriteLine("Press Enter");
if (Console.ReadKey().Key == ConsoleKey.Enter)
{
    Console.WriteLine("User pressed \"Enter\"");
}
于 2021-11-16T18:12:54.110 回答