C# arrow key input for a console app
A bit late now, but here's how to access keyboard state in a console application.
Note that it's not all managed code as it requires GetKeyState to be imported from User32.dll.
/// <summary>
/// Codes representing keyboard keys.
/// </summary>
/// <remarks>
/// Key code documentation:
/// http://msdn.microsoft.com/en-us/library/dd375731%28v=VS.85%29.aspx
/// </remarks>
internal enum KeyCode : int
{
/// <summary>
/// The left arrow key.
/// </summary>
Left = 0x25,
/// <summary>
/// The up arrow key.
/// </summary>
Up,
/// <summary>
/// The right arrow key.
/// </summary>
Right,
/// <summary>
/// The down arrow key.
/// </summary>
Down
}
/// <summary>
/// Provides keyboard access.
/// </summary>
internal static class NativeKeyboard
{
/// <summary>
/// A positional bit flag indicating the part of a key state denoting
/// key pressed.
/// </summary>
private const int KeyPressed = 0x8000;
/// <summary>
/// Returns a value indicating if a given key is pressed.
/// </summary>
/// <param name="key">The key to check.</param>
/// <returns>
/// <c>true</c> if the key is pressed, otherwise <c>false</c>.
/// </returns>
public static bool IsKeyDown(KeyCode key)
{
return (GetKeyState((int)key) & KeyPressed) != 0;
}
/// <summary>
/// Gets the key state of a key.
/// </summary>
/// <param name="key">Virtuak-key code for key.</param>
/// <returns>The state of the key.</returns>
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern short GetKeyState(int key);
}
var isUp = Console.ReadKey().Key == ConsoleKey.UpArrow;
or another example, just for your case:
while (true)
{
var ch = Console.ReadKey(false).Key;
switch(ch)
{
case ConsoleKey.Escape:
ShutdownRobot();
return;
case ConsoleKey.UpArrow:
MoveRobotUp();
break;
case ConsoleKey.DownArrow:
MoveRobotDown();
break;
}
}
System.Console.ReadKey(true).Key == ConsoleKey.UpArrow
You could put that into a spin, something like:
while(Running)
{
DoStuff();
System.Console.ReadKey(true).Key == ConsoleKey.UpArrow
Thread.Sleep(1)
}