来自Console.ReadKey()

时间:2019-08-15 10:02:06

标签: c# console-application

输出类似于:

 ]      [ Your input is: ffffffwwqqqwffasfffffffw
    >

当您使用BACKSPACE开始时,这是不可能的, 为什么会这样

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApp7
{
    class Program
    {
        public static string input;

        static Program()
        {
            input = string.Empty;
        }

        static void Main(string[] args)
        {
            while (true)
            {
                ConsoleKeyInfo consoleKeyInfo;

                Console.Clear();

                Console.Out.Write($"\r\n\t[ Your input is: {input} ]\r\n\r\n\t>");

                consoleKeyInfo = Console.ReadKey();

                if (consoleKeyInfo.Modifiers == default(ConsoleModifiers))
                    input += consoleKeyInfo.KeyChar;

                Thread.Sleep(250);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

退格是ReadKey处理的有效字符,当您将退格字符连接到字符串时,它将从输出中的字符串中删除最后一个字符。您可以检查所按下的键是否为退格键并将其忽略。

if (consoleKeyInfo.Modifiers == default(ConsoleModifiers) && consoleKeyInfo.Key != ConsoleKey.Backspace)
    input += consoleKeyInfo.KeyChar;