Console.Readline 为 运行 时输入的按键事件
Event by Key entered while Console.Readline is running
我正在开发一个项目,该项目通过在 Mac OS 上键入类似终端的命令来执行特定操作。问题是 Console.ReadLine
和 Console.ReadKey
方法不相互共享线程。
例如,
我正在创建一个程序,当我在使用 Console.ReadLine
.
键入字符串时按 ESC 键时该程序终止
我可以通过以下方式做到这一点:
ConsoleKeyInfo cki;
while (true)
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Escape)
break;
Console.Write(cki.KeyChar);
// do something
}
但该方法的问题在于,当您在控制台上键入时,按退格键不会删除输入字符串的最后一个字符。
为了解决这个问题,我可以保存输入的字符串,在按下退格键时初始化控制台屏幕,然后再次输出保存的字符串。但是,我想保存之前输入的字符串的记录,不想初始化。
如果有一种方法可以清除已经使用 Console.Write
打印的字符串的一部分,或者如果在使用 [= 输入字符串时按下特定键时会发生事件13=],以上问题都可以轻松解决
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);
示例取自 msdn 本身。
https://msdn.microsoft.com/en-us/library/system.consolekeyinfo.keychar(v=vs.110).aspx
我正在开发一个项目,该项目通过在 Mac OS 上键入类似终端的命令来执行特定操作。问题是 Console.ReadLine
和 Console.ReadKey
方法不相互共享线程。
例如,
我正在创建一个程序,当我在使用 Console.ReadLine
.
我可以通过以下方式做到这一点:
ConsoleKeyInfo cki;
while (true)
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Escape)
break;
Console.Write(cki.KeyChar);
// do something
}
但该方法的问题在于,当您在控制台上键入时,按退格键不会删除输入字符串的最后一个字符。
为了解决这个问题,我可以保存输入的字符串,在按下退格键时初始化控制台屏幕,然后再次输出保存的字符串。但是,我想保存之前输入的字符串的记录,不想初始化。
如果有一种方法可以清除已经使用 Console.Write
打印的字符串的一部分,或者如果在使用 [= 输入字符串时按下特定键时会发生事件13=],以上问题都可以轻松解决
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);
示例取自 msdn 本身。 https://msdn.microsoft.com/en-us/library/system.consolekeyinfo.keychar(v=vs.110).aspx