Created
January 30, 2021 23:17
-
-
Save nobuh/8b42b283b5bac20f156ca6aff84eb371 to your computer and use it in GitHub Desktop.
Key Input Sample for .NET 5 Console App
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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