7

I have written a simple program in C# in Visual Studio 2013. At the end of my program I instruct the user to:

"Please Press Enter to Exit the Program."

I would like to get the input from the keyboard on the next line and if ENTER is pressed, the program will quit.

Can anyone tell me how I can achieve this function?

I have tried the following code:

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

if(line == "enter")
{
    System.Environment.Exit(0);
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76

4 Answers4

10

Try following:

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

You can use a do-while too. More informations: Console.ReadKey()

DogeAmazed
  • 858
  • 11
  • 28
7

Use Console.ReadKey(true); like this:

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!
}
Philippe Paré
  • 4,279
  • 5
  • 36
  • 56
5

If you write the Program this way:

  • You don't need to call System.Environment.Exit(0);
  • Also you don't need to check for input key.

Example:

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

Another Example:

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();
        }
    }
}

Yet Another Example:

If you need, you can check if the value read by Console.ReadLine() is empty, then Environment.Exit(0);

//...
var line= Console.ReadLine();
if(string.IsNullOrEmpty(line))
    Environment.Exit(0)
else
    Console.WriteLine(line);
//...
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
1
Console.WriteLine("Press Enter");
if (Console.ReadKey().Key == ConsoleKey.Enter)
{
    Console.WriteLine("User pressed \"Enter\"");
}
Elenie
  • 21
  • 1