0

I'm practicing with C# on my road to become a developer, so I'm kinda new with all this. I'm writing a simple console app to get some practice mileage, using the challenges I run into to learn more about how to work with the language. Because I love D&D I made a simple app that rolls different dice with pseudorandom numbers, with the possibility of adding modifiers. It asks the user which kind of die he/she would like to roll, how many, if there's any modifiers etc. etc.

In short, here's my problem: I want to give the user the possibility to exit the program at any given time by pressing ESC, while otherwise functioning as normal and handling user input as normal.

My console app is dependent on user input. All it does is ask the user for input, and then do something with that input, like a calculator. There's at least 6+ different moments where the user is prompted for input (type of die, amount of dice, adding modifiers etc.). What I want to do is offer the user the possibility of exiting the program at any time by pressing ESC instead of inputting their data. Because there are so many prompts, I want to prevent adding a check for ESC at every prompt so the code doesn't get repetitive and clunky.

I tried multithreading with a listener for the ESC key, but I found that it 'stole' the first character of every user input prompt. If I press ESC, the program neatly exits just like I want to, but if I don't want to exit and just input my data, the first keystroke is missing because it was used to check for the ESC key.

Is there a way to check if it's the ESC key, and if it isn't, just keep the input where it was?

  • *"exiting the program at any time by pressing ESC instead of inputting their data"* - [google-fu](https://www.google.com/search?q=console.readline+c%23+interrupt+site:stackoverflow.com). – Sinatr May 05 '20 at 11:27
  • Does this answer your question? [Listen on ESC while reading Console line](https://stackoverflow.com/questions/31996519/listen-on-esc-while-reading-console-line) – Sinatr May 05 '20 at 11:28
  • @Sinatr I tried a bunch of methods I found around Google and StackOverflow but they all caused the first character of the user input to disappear. The only one I haven't tried is replacing the ReadLine() with a self-made method, but I wanted to see if there was any way around having to do that. – Merel van den Hurk May 06 '20 at 12:05
  • If it was something easy you would see it as an answer in the linked duplicate. You can try to setup [global keyboard hook](https://stackoverflow.com/q/15413172/1997232) and monitor for Esc key in parallel with `Console.ReadLine`. Then just [shutdown application](https://stackoverflow.com/q/5682408/1997232), hopefuly you will not run into [another problem](https://stackoverflow.com/q/9479573/1997232). – Sinatr May 06 '20 at 13:26

0 Answers0