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.
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.
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
I am having trouble figuring out how to break out of a loop that contains a switch statement.
i need to press 0 twice to exit the console why?
how can i fix it to exit from the first time
public void Start()
{
int choice = 0;
bool trueNumber = false;
do
{
ShowMenu(); // display the menu
Console.Write("Your Choice : ");
trueNumber = int.TryParse(Console.ReadLine(), out choice);
if (!trueNumber)
Console.WriteLine("Your Choice must be an integer. Try again.");
switch (choice) // select the relevant function based on user input
{
case 1:
CalculateCelsiusToFahrenheit();
break;
case 2:
CalculateFahrenheitToCelsius();
break;
case 0:
return; // exit when i press 0
default:
Console.WriteLine("Invalid Option: Choose 0, 1, or 2 Thank you ");
break;
}
} while (choice != 0);
}
If you are running this from an IDE (like Visual Studio), the default behavior for console applications is to end with a "Press any key to continue." so it waits with the output displayed.
related answer: VS setting
the following scenario is given:
Welcome screen appears. If user has read the welcome text he has 2 choices:
a) pressing ENTER to continue an getting the next text
b) pressing the E-Key in oder to leave the program
So my problem is:
how can I check if the user pressed the ENTER-Key?
what i tried so far - just as very primitive prototype
...var userInput= Console.ReadLine();
if (userInput == "\r")
{
Console.WriteLine("correct");
}
else
{
Console.WriteLine("wrong");
}....
I also tried it via Regex but I didn't make it run. Thanks for helping...
Just like this (with Console.ReadKey):
static void Main(string[] args)
{
Console.WriteLine("Hello Mr.Sun! Try press enter now:");
var userInput = Console.ReadKey();
if(userInput.Key == ConsoleKey.Enter)
{
Console.WriteLine("You pressed enter!");
} else
{
Console.WriteLine("You pressed something else");
}
}
Total beginner here, literally started learning programming for the first time in my life yesterday, so please don't judge!
I'm trying to make a program that allows the user to enter the name and score of videogames, then show these scores upon request. I'm trying to make a menu. I noticed the program would crash if the user presses enter without entering any number, and I wanted to avoid that, but I'm stuck. If I press enter it doesn't crash. However, if I enter 1 or 2, the menu keeps going anyways, and if I press enter without entering anything after that, then it crashes? I'm lost.
namespace videogaems
{
class Program
{
static void Main(string[] args)
{
menu();
}
static void menu()
{
int option = 0;
Console.WriteLine("Select what you want to do: ");
Console.WriteLine("1- add game");
Console.WriteLine("2- show game rating");
bool tryAgain = true;
while (tryAgain)
{
try
{
while (option != 1 || option != 2)
{
option = Convert.ToInt32(Console.ReadLine());
tryAgain = false;
}
}
catch (FormatException)
{
option = 0;
}
}
}
Convert.ToInt32(Console.ReadLine()) will throw an exception if the string cannot be converted to an integer. Instead, you should use int.TryParse, which takes in a string and an out parameter that gets set to the converted value (if successful). It returns a bool which indicates if it was successful or not.
For example, the following code will loop as long as int.TryParse fails, and when it succeeds, userInput will contain the converted number:
int userInput;
while (!int.TryParse(Console.ReadLine(), out userInput))
{
Console.WriteLine("Please enter a whole number");
}
Another option, however, is to simply use Console.ReadKey(), which returns a ConsoleKeyInfo object that represents the key that the user pressed. Then we can just check the value of the key character (and ignore any keys that are invalid).
For example:
static void Menu()
{
bool exit = false;
while (!exit)
{
Console.Clear();
Console.WriteLine("Select what you want to do: ");
Console.WriteLine(" 1: Add a game");
Console.WriteLine(" 2: Show game rating");
Console.WriteLine(" 3: Exit");
ConsoleKeyInfo userInput = Console.ReadKey();
Console.WriteLine();
switch (userInput.KeyChar)
{
case '1':
// Code to add a game goes here (call AddGame() method, for example)
Console.Clear();
Console.WriteLine("Add a game was selected");
Console.WriteLine("Press any key to return to menu");
Console.ReadKey();
break;
case '2':
// Code to show a game rating goes here (call ShowRating(), for example)
Console.Clear();
Console.WriteLine("Show game rating was selected");
Console.WriteLine("Press any key to return to menu");
Console.ReadKey();
break;
case '3':
// Exit the menu
exit = true;
break;
}
}
}
I have a basic console application. Users can select from a numbered menu, 1-5. If they press ESC the program closes but if they don't press ESC a switch is used to determine which option they chose by which string they input (1, 2, 3, 4 or 5).
This code isn't working:
static string mainMenu()
{
string menuOption;
// get user input
ConsoleKeyInfo option = Console.ReadKey();
if (option.Key == ConsoleKey.Escape)
{
Environment.Exit(0);
}
return menuOption = Console.ReadLine();
}
How can I get the string value of what the user input in to menuOption whilst also checking if the user pressed ESC?
You can use menuOption = option.KeyChar.ToString();
If your options are only single character, then its better if you return a character instead of string and then have the switch statement on character. Your method can be like:
static char mainMenu()
{
ConsoleKeyInfo option = Console.ReadKey();
if (option.Key == ConsoleKey.Escape)
{
Environment.Exit(0);
}
return option.KeyChar;
}
and then you can use it in switch statement like:
char option = mainMenu();
switch (option)
{
case '1':
//...........
}
Or use the method directly in switch statement like:
switch (mainMenu())
I am trying to make a simple console game that starts with a title screen. The user inputs 'N' for a new game, 'L' to load a game, or 'E' to exit. I have this set up as a switch, but I need to know how to make the program ignore any input other than the aforementioned keys. I've Googled this question but didn't find an answer. Please help if you can.
I don't see much point in posting the code as 10 lines of a simple switch probably wouldn't be terribly helpful to solving the problem. Also, if there would be an easier / more efficient way than a switch, I would love to know.
Thanks.
You can use a default: statement to handle the other (unknown) cases:
switch(inputString.ToLower())
{
case "n":
// Handle new
break;
//.. handle known cases
default:
Console.WriteLine("Unknown option chosen. Please enter valid option:");
// Re-read values, etc?
break;
}
Anything not specified in one of your other cases will fall into the default case, which you can then use to prompt for valid input.
If you want to actually ignore all keys other than valid ones you could do something like this:
public static char ReadKey(IEnumerable<char> validKeys)
{
var validKeySet = new HashSet<char>(validKeys);
while (true)
{
var key = Console.ReadKey(true);
if (validKeySet.Contains(key.KeyChar))
{
//you could print it out if you wanted.
//Console.Write(key.KeyChar);
return key.KeyChar;
}
else
{
//you could print an error message here if you wanted.
}
}
}
When you use ReadKey(true) the true indicated that it will intercept that key and not display it on the console. This gives you the option of determining if it's valid or invalid.
If a switch statement does not have a default block, and if the expression being switched on does not match any of the case blocks, the switch statement does nothing.
When you have only 3 cases, a switch isn't much more efficient than just a simple if-else construct.
if (input == "N")
{
// New game
}
else if (input == "L")
{
// Load game
}
else if (input == "E")
{
// Exit game
}
// if none of the cases match, the input is effectively ignored.
If you insist on using a switch, then your construct is very similar:
switch (input)
{
case "N":
//New Game
break;
case "L":
//Load Game
break;
case "E":
//Exit Game
break;
default:
//Do nothing (ignore unmatched inputs)
break;
}
Thanks for the replies, guys. I managed to solve the problem by doing the following:
static void titleInput()
{
ConsoleKeyInfo titleOption = Console.ReadKey(true);
switch (titleOption.Key)
{
case ConsoleKey.N:
Console.Clear();
break;
case ConsoleKey.L:
break;
case ConsoleKey.E:
Environment.Exit(0);
break;
default:
titleInput();
break;
}
}
I'm not sure how 'proper' this is, but it does what I need it to do. Any keys other than 'N', 'L', and 'E' no longer do anything.