Exit Console App at any Time During Any Input (C#)

前端 未结 2 1244
独厮守ぢ
独厮守ぢ 2021-01-17 05:23

I have a relatively large console app with multiple menu\'s and user inputs. I need to create a way for a user to \"Quit\" or \"Back\" at any time essentially break;

2条回答
  •  离开以前
    2021-01-17 06:01

    Simple Answer: Just use ctrl + C to exit the Console anytime (no code needed)

    If you want to do some clean up operations before existing: then you are probably looking for Console.CancelKeyPress Event

    private static volatile bool cancelRequested = false;
    
    public static void Main(string[] args)
    {
        Console.CancelKeyPress += new ConsoleCancelEventHandler(ExitConsole);
        while (!cancelRequested)
        {
            // here your program will continue a WHOLE WHILE loop until user requests exit by 
            // pressing either the C console key (C) or the Break key 
            // (Ctrl+C or Ctrl+Break).
    
            UserInput #1;
            UserInput #2;
            UserInput #3;
        }
    }
    
    static void ExitConsole(object sender, ConsoleCancelEventArgs e)
    {
        e.Cancel = true;
        cancelRequested = true;
    }
    

    Here you can find relative answers.

提交回复
热议问题