[SOURCE][C#] Console Menu - DragonHunter - Nov 7, 2010
Hey guys, this is a simple Console Menu i've made yesterday
have fun with the code 😎
Code public class CMenu
{
private SortedList<int, string[]> menu;
public int CurrentMenu = 0;
public int SelectedIndex = 0;
private Thread KeyHandlerThread;
public ConsoleKeyInfo KeyPressed;
private ConsoleColor SelectColor;
private ConsoleColor NonSelectColor;
public CMenu()
{
menu = new SortedList<int,string[]>();
KeyHandlerThread = new Thread(new ThreadStart(KeyPressHandler));
KeyHandlerThread.Start();
SelectColor = ConsoleColor.Green;
NonSelectColor = ConsoleColor.Gray;
}
public void Refresh()
{
Console.Clear();
Console.WriteLine("");
for(int y = 0; y < menu[CurrentMenu].Length; y++)
{
if(SelectedIndex == y)
Console.ForegroundColor = SelectColor;
else
Console.ForegroundColor = NonSelectColor;
Console.Write(menu[CurrentMenu][y].ToString().PadLeft(12));
Console.ResetColor();
}
Console.WriteLine("");
Console.WriteLine("");
}
private void KeyPressHandler()
{
while(true)
{
KeyPressed = Console.ReadKey();
if(KeyPressed.Key == ConsoleKey.RightArrow)
{
if(SelectedIndex < menu[CurrentMenu].Length - 1)
SelectedIndex++;
}
else if(KeyPressed.Key == ConsoleKey.LeftArrow)
{
if(SelectedIndex > 0)
SelectedIndex--;
}
}
}
public void AddMenu(int index)
{
menu.Add(index, new string[] { });
}
public void AddSubMenu(int index, string[] SubMenu)
{
menu[index] = SubMenu;
}
}
Usage:
Code CMenu menu = new CMenu();
menu.AddMenu(0); //create new menu with ID 0
menu.AddSubMenu(0, new string[] { "Goto Menu2", "Goto Menu2" });
//Second menu
menu.AddMenu(1); //create new menu with ID 1
menu.AddSubMenu(1, new string[] { "Goto Menu1", "[Back]" });
while(true)
{
Thread.Sleep(50);
menu.Refresh();//lets refresh the menu...
//put here ur own code to show stuff at the console...
switch (menu.CurrentMenu)
{
case 0:
Console.WriteLine("-- MENU 1 --");
switch (menu.SelectedIndex)
{
case 0:
if(menu.KeyPressed.Key == ConsoleKey.Enter)
{
menu.CurrentMenu = 1;
menu.KeyPressed = new ConsoleKeyInfo();
}
Console.WriteLine("Hello, This Console menu is created by DragonHunter");
break;
case 1:
if(menu.KeyPressed.Key == ConsoleKey.Enter)
{
menu.CurrentMenu = 1;
menu.KeyPressed = new ConsoleKeyInfo();
}
Console.WriteLine("Please leave the credits when ull share it somewhere else");
break;
}
break;
case 1:
Console.WriteLine("-- MENU 2 --");
switch (menu.SelectedIndex)
{
case 0:
if (menu.KeyPressed.Key == ConsoleKey.Enter)
{
menu.CurrentMenu = 0;
menu.KeyPressed = new ConsoleKeyInfo();
}
Console.WriteLine("This will let us navigate back to menu1");
break;
case 1:
if (menu.KeyPressed.Key == ConsoleKey.Enter)
{
menu.CurrentMenu--; //easy ha ?
menu.KeyPressed = new ConsoleKeyInfo();
}
Console.WriteLine("let us navigate back to our first menu :P");
break;
}
break;
}
}
* - Local Celeb - Nov 7, 2010
Wow man. This is a brilliant idea!
I added this to my compilation thread of C#. This can be used for MANY Things.
|