0

In a simple console app that requests the users input, I'm asking for a user input. That input is then saved into a variable for later use.

How can I display the input while it's being typed into the console, but hide it after its been submitted?

For example:

class Program
{
    static void Main()
    {

        string input = null;

        Console.WriteLine("Type Something: ");
        input = Console.ReadLine();
        Console.WriteLine("You Typed" + input);
    }
}

After running the above code, the output below is printed to the console is:

Type Something:
abc 123 
You Typedabc 123

How can I adapt this code so as, after the user has typed and submitted the input, it does not appear in the output?

devklick
  • 2,000
  • 3
  • 30
  • 47

1 Answers1

3

I've done this before by creating a method that moves the cursor to the previous lines, writes whitespace over the line, and resets the cursor to the beginning of the line again:

private static void DeletePrevConsoleLine()
{
    if (Console.CursorTop == 0) return;
    Console.SetCursorPosition(0, Console.CursorTop - 1);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - 1);
}

Usage:

string input = null;

Console.WriteLine("Type Something: ");
input = Console.ReadLine();
DeletePrevConsoleLine();
Console.WriteLine("You Typed: " + input);

Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
Rufus L
  • 36,127
  • 5
  • 30
  • 43