Skip to content

Instantly share code, notes, and snippets.

@nobuh
Created January 30, 2021 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nobuh/8b42b283b5bac20f156ca6aff84eb371 to your computer and use it in GitHub Desktop.
Save nobuh/8b42b283b5bac20f156ca6aff84eb371 to your computer and use it in GitHub Desktop.
Key Input Sample for .NET 5 Console App
using System;
namespace KiloSharp
{
class Program
{
static void enableRawMode()
{
Console.CursorVisible = false;
}
static void disableRawMode()
{
Console.CursorVisible = true;
}
static int Main(string[] args)
{
enableRawMode();
Console.Clear();
// if ctrl key is pressed, console terminal respons even without printing it.
// So we need the cancel handler to disable the reaction of ctrl keys.
// However CTRL-Z is still alive.
Console.CancelKeyPress += new ConsoleCancelEventHandler(controlKeyHandler);
ConsoleKeyInfo c;
do {
while (! Console.KeyAvailable) {
}
c = Console.ReadKey(true);
if ((c.Modifiers & ConsoleModifiers.Control) != 0) {
Console.Write((int)c.KeyChar);
} else {
Console.Write(c.KeyChar);
}
} while (c.Key != ConsoleKey.Q);
disableRawMode();
return 0;
}
protected static void controlKeyHandler(object sender, ConsoleCancelEventArgs args)
{
args.Cancel = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment