Instantly share code, notes, and snippets.

@Brogie /ConsoleMenu
Last active Jan 26, 2017

What would you like to do?
This will make a menu for the console in C#
static int Menu(string[] inArray) {
bool loopComplete = false;
int topOffset = Console.CursorTop;
int bottomOffset = 0;
int selectedItem = 0;
ConsoleKeyInfo kb;
Console.CursorVisible = false;
//this will resise the console if the amount of elements in the list are too big
if ((inArray.Length) > Console.WindowHeight) {
throw new Exception("Too many items in the array to display");
* Drawing phase
* */
while (!loopComplete) {//This for loop prints the array out
for (int i = 0; i < inArray.Length; i++) {
if (i == selectedItem) {//This section is what highlights the selected item
Console.BackgroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine("-" + inArray[i]);
} else {//this section is what prints unselected items
Console.WriteLine("-" + inArray[i]);
bottomOffset = Console.CursorTop;
* User input phase
* */
kb = Console.ReadKey(true); //read the keyboard
switch (kb.Key) { //react to input
case ConsoleKey.UpArrow:
if (selectedItem > 0) {
} else {
selectedItem = (inArray.Length - 1);
case ConsoleKey.DownArrow:
if (selectedItem < (inArray.Length - 1)) {
} else {
selectedItem = 0;
case ConsoleKey.Enter:
loopComplete = true;
//Reset the cursor to the top of the screen
Console.SetCursorPosition(0, topOffset);
//set the cursor just after the menu so that the program can continue after the menu
Console.SetCursorPosition(0, bottomOffset);
Console.CursorVisible = true;
return selectedItem;

This comment has been minimized.

prbubblegum commented Oct 16, 2016

Hello, sorry i am a great noob, but how do you create a Main and call a function here and pass the values for menu options. I am trying to understand but i fail.


This comment has been minimized.


Brogie commented Jan 26, 2017

Sorry for the long reply, the menu options are passed in an array of strings and the function returns the index of the selected option. Look here for some more information

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment