如何阅读“进入”从键盘退出程序

本文关键字:键盘 退出程序 进入 何阅读 | 更新日期: 2023-09-27 18:13:16

我在Visual Studio 2013中用c#编写了一个简单的程序。在程序的最后,我指示用户:

"请按Enter键退出程序。"

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

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

我尝试了以下代码:

Console.WriteLine("Press ENTER to close console......");
String line = Console.ReadLine();
if(line == "enter")
{
    System.Environment.Exit(0);
}

如何阅读“进入”从键盘退出程序

尝试如下:

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

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

像这样使用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!
}

如果你这样写程序:

  • 你不需要调用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);
//...
Console.WriteLine("Press Enter");
if (Console.ReadKey().Key == ConsoleKey.Enter)
{
    Console.WriteLine("User pressed '"Enter'"");
}