I am developing a project that does something specific by typing a command like a terminal on Mac OS. The problem is that Console.ReadLine
and Console.ReadKey
methods do not share threads with each other.
For example,
I am creating a program that terminates when I press ESC while I'm typing a string using Console.ReadLine
.
I can do this in the following way:
ConsoleKeyInfo cki;
while (true)
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Escape)
break;
Console.Write(cki.KeyChar);
// do something
}
But the problem with that method is that pressing the Backspace key does not erase the last character of the input string as you type on the console.
To solve this problem, I can save the input string, initialize the console screen when the Backspace key is pressed, and then output the saved string again. However, I want to save the records of the strings that were previously input, I do not want to initialize.
If there is a way to clear a portion of a string that has already been printed using Console.Write
, or if there is an event that occurs when a specific key is pressed while inputting a string using Console.ReadLine
, the above problems can be solved easily.
string inputString = String.Empty;
do {
keyInfo = Console.ReadKey(true);
// Handle backspace.
if (keyInfo.Key == ConsoleKey.Backspace) {
// Are there any characters to erase?
if (inputString.Length >= 1) {
// Determine where we are in the console buffer.
int cursorCol = Console.CursorLeft - 1;
int oldLength = inputString.Length;
int extraRows = oldLength / 80;
inputString = inputString.Substring(0, oldLength - 1);
Console.CursorLeft = 0;
Console.CursorTop = Console.CursorTop - extraRows;
Console.Write(inputString + new String(' ', oldLength - inputString.Length));
Console.CursorLeft = cursorCol;
}
continue;
}
// Handle Escape key.
if (keyInfo.Key == ConsoleKey.Escape) break;
Console.Write(keyInfo.KeyChar);
inputString += keyInfo.KeyChar;
} while (keyInfo.Key != ConsoleKey.Enter);
Example taken from the msdn itself. https://msdn.microsoft.com/en-us/library/system.consolekeyinfo.keychar(v=vs.110).aspx