【问题标题】:Event by Key entered while Console.Readline is running在 Console.Readline 运行时输入的按键事件
【发布时间】:2017-08-02 17:10:25
【问题描述】:

我正在开发一个项目,该项目通过在 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 键不会删除输入字符串的最后一个字符。

为了解决这个问题,我可以保存输入的字符串,按下退格键时初始化控制台屏幕,然后再次输出保存的字符串。但是,我想保存之前输入的字符串的记录,我不想初始化。

如果有一种方法可以清除已使用Console.Write 打印的字符串的一部分,或者如果在使用Console.ReadLine 输入字符串时按下特定键时发生事件,则上述问题很容易解决。

【问题讨论】:

    标签: c# console readkey


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      相关资源
      最近更新 更多