Todor Yanev
Todor Yanev

Reputation: 1

Strange behaviour from Console.ReadKey()

The output looks something like:

 ]      [ Your input is: ffffffwwqqqwffasfffffffw
    >

when you use BACKSPACE which shouldn't be possible to begin with, why is this happening

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

Upvotes: 2

Views: 233

Answers (1)

Lukas
Lukas

Reputation: 498

Backspace is a valid char for ReadKey to process, and when you concatenate a backspace char to the string, it will remove the last character from the string in the output. You can check whether the key that was pressed was a backspace and ignore it.

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

Upvotes: 1

Related Questions