Mayora13
Mayora13

Reputation: 33

How to display multiple text lines before user inputs any text for console app

In my C# console application i would like to display multiple lines of text before user enters any input like below:

Username:
Password:

with the cursor next to username.

Calling Console.ReadLine() in between the two Write() function only displays the password line once user input has been entered for username.

I also have to try and keep it from messing with the code that displays the password as * while typing.

Any help would be much appreciated. I've provided code for the whole method though it's unlikely the bottom part is useful.

public void mainMenu()
{  
    String userNameLbl = "Username:";
    String pWordLbl = "Password:";

    Console.Write(
        String.Format(
           "{0," + ((Console.WindowWidth / 4) + userNameLbl.Length - 3) + "}", 
           userNameLbl));

    userName = Console.ReadLine();

    Console.Write(
         String.Format(
             "{0," + ((Console.WindowWidth / 4) + pWordLbl.Length - 3) + "}",
             pWordLbl));

    //password appears as *
    do
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        // as long as key is not backspace or enter
        if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
        {
            // add character to passWord and print '*'
            passWord += key.KeyChar;
            Console.Write("*");
        }
        else
        {
            // backspacing
            if (key.Key == ConsoleKey.Backspace && passWord.Length > 0)
            {
                passWord = passWord.Substring(0, (passWord.Length - 1));
                Console.Write("\b \b");
            }

            if(CorrectLogin(userName, passWord))
            {
                Console.WriteLine("\nValid Credentials! Press Enter to Continue");
                ConsoleKeyInfo enterKey = Console.ReadKey(true);
                if (enterKey.Key == ConsoleKey.Enter)
                {
                    Console.Clear();
                    switchMenu();
                }
            }                    
            else if (!(CorrectLogin(userName, passWord)))
            {
                Console.WriteLine("\nInvalid Credentials... Press Enter to Retry");
                        passWord = "";
                        ConsoleKeyInfo enterKey = Console.ReadKey(true);
                        if(enterKey.Key == ConsoleKey.Enter){
                            Console.Clear();
                            mainMenu();
            }    
        }
        break;        
    } while (true);
}

Upvotes: 1

Views: 391

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70701

In the olden days, if we wanted to present the user with a form, a text screen was the only thing we even had. It involved repositioning the screen cursor as needed before each text element was drawn or user input was provided.

You can still do basically the same thing with a .NET console program, using the Console.SetCursorPosition() method. Here's a simple proof-of-concept demonstrating the basic idea:

static void Main(string[] args)
{
    string promptFormat = "{0}: ";
    string[] fieldNames = { "Username", "Password" };
    string[] fieldPrompts = fieldNames.Select(s => string.Format(promptFormat, s)).ToArray();
    int columnWidth = fieldPrompts.Max(s => s.Length);

    Console.Clear();
    foreach (string prompt in fieldPrompts)
    {
        Console.WriteLine(prompt);
    }

    Dictionary<string, string> fieldValues = new Dictionary<string, string>();

    int line = 0;
    foreach (string field in fieldNames)
    {
        Console.SetCursorPosition(columnWidth, line++);
        string userValue = Console.ReadLine();
        fieldValues.Add(field, userValue);
    }

    Console.WriteLine();
    Console.WriteLine("You entered the following:");

    foreach (var kvp in fieldValues)
    {
        Console.WriteLine($"Field: \"{kvp.Key}\", Value: \"{kvp.Value}\"");
    }
}

You would of course need to adapt the user input routine for your password-style input. That level of detail is outside the scope of your actual question, so I didn't bother to include it in the above.

And naturally, you could just hard-code all the locations as well. In fact, that's often how it was done in the olden days too. The code to automatically lay out the user input position is just an easy little tweak to make the code a bit more general purpose. Hopefully you can see how you could include even more automatic-layout features, if you really wanted to.

Upvotes: 4

Related Questions