Search code examples
c#stringconsole-applicationkeyboard-eventsbackspace

Backspace won't function correctly with StringBuilder in C# console


I am trying to create a screen where the user would be able to write down their name with StringBuilder.

The problems I have is with the functionality of backspace. I can remove all letters except the first letter that was pressed. Also, it seems like I can press whatever character and it would be submitted.

ConsoleKeyInfo cki = new ConsoleKeyInfo();
bool enterPressed = false;
StringBuilder name = new StringBuilder();
int temp = 61;
do
{
    Console.SetCursorPosition(temp, 14);
    cki = Console.ReadKey(true);
    if (cki.Key == ConsoleKey.Enter && name.Length > 0 && name.Length < 12)
    {
        enterPressed = true;
        Console.SetCursorPosition(61, 18);
        Console.Write(name);
    }
    else if ("qwertyuiopasdfghjklzxcvbnm".Contains(cki.KeyChar) && name.Length < 12)
    {
         name.Append(cki.KeyChar);
         Console.Write(cki.KeyChar);
         temp += 1;
    }
    else if(cki.Key == ConsoleKey.Backspace && name.Length > 0)
    {
         name.Remove(name.Length-1, 1);
         Console.Write("\b \b");
    }
} while (name.Length > 0 && !enterPressed);

Solution

  • You forgot to do temp--; This code snippet should solve your problem

                    name.Remove(name.Length - 1, 1);
                    temp--;
                    Console.Write("\b \b");