Skip to content

Instantly share code, notes, and snippets.

@timgaunt
Created May 18, 2012 15:17
Show Gist options
  • Save timgaunt/2725813 to your computer and use it in GitHub Desktop.
Save timgaunt/2725813 to your computer and use it in GitHub Desktop.
Quick menu system for console applications
namespace TheSiteDoctor.Example
{
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static readonly IEnumerable<Tuple<string, string, Action>> menu = new List<Tuple<string, string, Action>>
{
// Call a method without any parameters
new Tuple<string, string, Action>("s", "Do something", SomeMethod),
// Call a using a lamda
new Tuple<string, string, Action>("e", "Do something else", () =>
{
Console.WriteLine("Something else has been done");
Console.WriteLine("Something else has been done again");
}),
// Prints a blank line
null,
new Tuple<string, string, Action>("m", "Display this menu", ShowMenu),
};
private static void ShowMenu()
{
Console.WriteLine("=========================================");
Console.WriteLine("Keyboard Shortcuts:");
foreach (var item in menu)
{
if (item == null)
Console.WriteLine();
else
Console.WriteLine(string.Format("{0} : {1}", item.Item1.PadRight(5), item.Item2));
}
Console.WriteLine("q : Quit");
Console.WriteLine("=========================================");
}
static int Main()
{
Console.Clear();
SetExceptionHandler();
ShowMenu();
string cmd;
while ((cmd = Console.ReadLine().ToLower()) != "q")
{
var item = menu.FirstOrDefault(i => i != null && i.Item1.Equals(cmd));
if (item != null)
item.Item3();
else
Console.WriteLine("Sorry, couldn't find that command");
Console.WriteLine("Finished - Enter 'm' to redisplay menu");
}
return 0;
}
private static void SomeMethod()
{
Console.WriteLine("Something has been done");
}
private static void SetExceptionHandler()
{
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
var ex = (Exception)e.ExceptionObject;
Console.WriteLine("==== ************** ====");
Console.WriteLine("== EXCEPTION OCCURRED ==");
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
Console.WriteLine("==== ************** ====");
Environment.Exit(1);
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment