在Console.Readline运行时输入Key的事件

时间:2017-08-02 17:10:25

标签: c# console readkey

我正在开发一个项目,通过在Mac OS上键入类似终端的命令来执行某些操作。问题是Console.ReadLineConsole.ReadKey方法不会彼此共享线程。

例如, 我正在创建一个程序,当我使用Console.ReadLine键入字符串时按ESC键终止。

我可以通过以下方式执行此操作:

ConsoleKeyInfo cki;
while (true)
{
    cki = Console.ReadKey(true);
    if (cki.Key == ConsoleKey.Escape)
        break;

    Console.Write(cki.KeyChar);

    // do something
}

但该方法的问题在于,当您在控制台上键入时,按Backspace键不会删除输入字符串的最后一个字符。

要解决此问题,我可以保存输入字符串,在按下Backspace键时初始化控制台屏幕,然后再次输出保存的字符串。但是,我想保存以前输入的字符串的记录,我不想初始化。

如果有办法清除已使用Console.Write打印的字符串的一部分,或者在使用{{1}输入字符串时按下特定键时发生了事件},上述问题可以轻松解决。

1 个答案:

答案 0 :(得分:1)

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