Home > front end >  Exit program after pressing escape button C#
Exit program after pressing escape button C#

Time:12-14

I need a way so user can exit the program by pressing escape button, so CancelKeyPress event doesn't work here. It is very important that the user can quit at any time they want.

I really have no idea how to do it as I am beginner, so I count on you. Thanks in advance.

CodePudding user response:

What i do when i make a Console application is a switch statement for exit.


switch (choice)
{
  case "1":
    util.Option();
    break;
  .
  .
  .

   case "q":
     System.Environment.Exit(1);

   default:
     break;             
}

System.Environment.Exit(1);can help you exit your console.

CodePudding user response:

Based on your description, I think you have solved the following code:

static void Main(string[] args)
{
    ConsoleKeyInfo CurrentInputKey;

    while(true)
    {
        // Your Other Codes
        Console.WriteLine("\rHello C# Developer.");
        CurrentInputKey = Console.ReadKey();

        if(CurrentInputKey != null && CurrentInputKey.Key == ConsoleKey.Escape)
        {
            Console.WriteLine("Exit ...");
            System.Environment.Exit(0);
        }
    }
}
  • Related