This is the code:
ConsoleKeyInfo cki;
while((cki = Console.ReadKey(true)).Key != ConsoleKey.Escape)
{
Console.WriteLine(cki.Key);
}
When i run it from cmd or powershell with dotnet run everything works fine. However when i run it from Git Bash it throws the following exception:
Unhandled exception. System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read.
ReadKey() Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window. public: static ConsoleKeyInfo ReadKey(); C# Copy.
ReadKey() Method makes the program wait for a key press and it prevents the screen until a key is pressed. In short, it obtains the next character or any key pressed by the user.
Presumably, then, Git Bash is using IO redirection - which it is allowed to do - and the others ... aren't. The solution, then, is to use Read
rather than ReadKey
- at least if redirection is in play. You can probably detect this via Console.IsInputRedirected
- and choose the most useful strategy for what is possible, but: you won't be able to detect keys in the same way, so you may need to have a slightly different user-experience in this scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With