-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConsoleMenu.cs
66 lines (56 loc) · 1.97 KB
/
ConsoleMenu.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Collections.Generic;
namespace SurfingTheCode.DotNetRocks
{
public static class ConsoleMenu
{
public static T Prompt<T>(List<T> items)
{
bool loopComplete = false;
int topOffset = Console.CursorTop;
int bottomOffset = 0;
int selectedItem = 0;
ConsoleKeyInfo kb;
Console.CursorVisible = false;
if (items.Count > Console.WindowHeight)
{
throw new Exception("Too many items to display");
}
while (!loopComplete)
{
for (int i = 0; i < items.Count; i++)
{
if (i == selectedItem)
{
Console.BackgroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.Black;
Console.WriteLine(" - " + items[i]);
Console.ResetColor();
}
else
{
Console.WriteLine(" - " + items[i]);
}
}
bottomOffset = Console.CursorTop;
kb = Console.ReadKey(true);
switch (kb.Key)
{
case ConsoleKey.UpArrow:
selectedItem = selectedItem > 0 ? selectedItem - 1 : items.Count - 1;
break;
case ConsoleKey.DownArrow:
selectedItem = selectedItem < items.Count - 1 ? selectedItem + 1 : 0;
break;
case ConsoleKey.Enter:
loopComplete = true;
break;
}
Console.SetCursorPosition(0, topOffset);
}
Console.SetCursorPosition(0, bottomOffset);
Console.CursorVisible = true;
return items[selectedItem];
}
}
}