简体   繁体   English

使用Console.ReadKey()时不清除退格键

[英]Backspace not erasing when using Console.ReadKey()

I have this simple code: 我有这个简单的代码:

    static void Main(string[] args)
    {
        while (!System.Console.KeyAvailable)
        {
            var key = System.Console.ReadKey(false);
        }
    }

When the user presses Backspace , the cursor just moves back but does not erase the last character. 当用户按下Backspace时 ,光标将向后移动,但不会删除最后一个字符。

I read some people just check if the input is Backspace and call Console.Write(" \\b") to erase, but I don't know if this is the best way to resolve. 我读过一些人,只是检查输入是否为Backspace并调用Console.Write(" \\b")进行擦除,但是我不知道这是否是解决问题的最佳方法。

If I read input using Console.Read() or Console.ReadLine() , the character is erased when Backspace is pressed. 如果我使用Console.Read()Console.ReadLine()读取输入, Console.Read() Backspace键时将删除该字符。

Why does the Backspace key change its behaviour when using ReadKey() ? 为什么在使用ReadKey()Backspace键会更改其行为?

When you use ReadKey() you are telling .NET you want the raw input and for it to not do any processing on it. 当您使用ReadKey()您在告诉.NET您想要原始输入,并且不要对其进行任何处理。 You can even tell .NET to not echo the key to the screen (via the parameter to the method). 您甚至可以告诉.NET(通过方法的参数)不要将键回显到屏幕。

If you use Read() or ReadLine() , you are instead telling .NET you want the input as obtained by the console logic, which includes the console imposing its own behavior on the input, such as erasing characters when the backspace key is pressed. 如果使用Read()ReadLine() ,则改为告诉.NET,您希望输入由控制台逻辑获取,该逻辑包括控制台将其自身的行为强加到输入上,例如在按下Backspace键时擦除字符。

Two different methods for obtaining input, two different outcomes. 获得输入的两种不同方法,两种不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM