Skip to content

Instantly share code, notes, and snippets.

@Brogie
Last active January 26, 2017 16:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Brogie/34dba368a34c57049b46 to your computer and use it in GitHub Desktop.
Save Brogie/34dba368a34c57049b46 to your computer and use it in GitHub Desktop.
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]);
Console.ResetColor();
} 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) {
selectedItem--;
} else {
selectedItem = (inArray.Length - 1);
}
break;
case ConsoleKey.DownArrow:
if (selectedItem < (inArray.Length - 1)) {
selectedItem++;
} else {
selectedItem = 0;
}
break;
case ConsoleKey.Enter:
loopComplete = true;
break;
}
//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;
}
@prbubblegum
Copy link

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.

@Brogie
Copy link
Author

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 http://www.stumblingthroughprogramming.co.uk/2015/02/making-menu-for-console-in-c-part-1.html

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