【问题标题】:How to read "Enter" from the keyboard to exit program如何从键盘读取“Enter”以退出程序
【发布时间】:2015-09-18 15:34:08
【问题描述】:

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

“请按 Enter 键退出程序。”

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

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

我尝试了以下代码:

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

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

【问题讨论】:

  • 也许是一个微不足道的答案,但Console.ReadLine() 不能解决问题?你需要什么?
  • @RezaAghaei 我用我尝试过的代码更新了问题。
  • 答案是 Console.Readline()

标签: c# visual-studio exit console.readline


【解决方案1】:

尝试以下操作:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果你这样写程序:

      • 您无需致电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);
      //...
      

      【讨论】:

        【解决方案4】:
        Console.WriteLine("Press Enter");
        if (Console.ReadKey().Key == ConsoleKey.Enter)
        {
            Console.WriteLine("User pressed \"Enter\"");
        }
        

        【讨论】:

          猜你喜欢
          • 2020-02-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多