【问题标题】:Strange behaviour from Console.ReadKey()Console.ReadKey() 的奇怪行为
【发布时间】:2019-12-21 19:05:11
【问题描述】:

输出看起来像:

 ]      [ 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);
            }
        }
    }
}

【问题讨论】:

    标签: c# console-application


    【解决方案1】:

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

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

    【讨论】:

    • “当你将退格字符连接到字符串时,它会从字符串中删除最后一个字符”我不这么认为。它应该只在字符串中附加一个退格字符。
    • 这就是我所说的意图,我指的是输出;我会改写它。
    猜你喜欢
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2015-07-20
    • 2010-10-03
    • 2021-07-12
    • 2013-10-04
    相关资源
    最近更新 更多