I'm writing a .NET Core console application. I wanted to limit console input to a certain number of maximum characters for each input. I have some code that does this by building a string with Console.ReadKey()
instead of Console.ReadLine()
Everything worked perfectly testing it on Windows. Then, when I deployed to a Raspberry Pi 3 running Raspbian, I quickly encountered all sorts of problems. I remembered that Linux handles line endings differently from Windows, and it seems backspaces are handled differently as well. I changed the way I handled those, going off the ConsoleKey instead of the character, and the newline problem went away, but backspaces only sometimes register. Also, sometimes characters get outputted to the console outside of my input box, even though I set the ReadKey to not output to the console on its own. Am I missing something about how Linux handles console input?
//I replaced my calls to Console.ReadLine() with this. The limit is the
//max number of characters that can be entered in the console.
public static string ReadChars(int limit)
{
string str = string.Empty; //all the input so far
int left = Console.CursorLeft; //store cursor position for re-outputting
int top = Console.CursorTop;
while (true) //keep checking for key events
{
if (Console.KeyAvailable)
{
//true to intercept input and not output to console
//normally. This sometimes fails and outputs anyway.
ConsoleKeyInfo c = Console.ReadKey(true);
if (c.Key == ConsoleKey.Enter) //stop input on Enter key
break;
if (c.Key == ConsoleKey.Backspace) //remove last char on Backspace
{
if (str != "")
{
tr = str.Substring(0, str.Length - 1);
}
}
else if (c.Key != ConsoleKey.Tab && str.Length < limit)
{
//don't allow tabs or exceeding the max size
str += c.KeyChar;
}
else
{
//ignore tabs and when the limit is exceeded
continue;
}
Console.SetCursorPosition(left, top);
string padding = ""; //padding clears unused chars in field
for (int i = 0; i < limit - str.Length; i++)
{
padding += " ";
}
//output this way instead
Console.Write(str + padding);
}
}
return str;
}