Search code examples
c#.netinputconsoleconsole-application

How to set default input value in .Net Console App?


How can you set a default input value in a .net console app?

Here is some make-believe code:

Console.Write("Enter weekly cost: ");
string input = Console.ReadLine("135"); // 135 is the default. The user can change or press enter to accept
decimal weeklyCost = decimal.Parse(input);

Of course, I don't expect it to be this simple. I am betting on having to do some low-level, unmanaged stuff; I just don't know how.

EDIT

I know I can replace no input with the default. That's not what I am asking about. I am trying to LEARN what's involved in achieving the behavior I described: giving the user an editable default. I'm also not worried about input validation; my question has nothing to do with that.


Solution

  • I believe that you will have manage this manually by listening to each key press:

    Quickly thown together example:

       // write the initial buffer
       char[] buffer = "Initial text".ToCharArray();
       Console.WriteLine(buffer);
    
       // ensure the cursor starts off on the line of the text by moving it up one line
       Console.SetCursorPosition(Console.CursorLeft + buffer.Length, Console.CursorTop - 1);
    
       // process the key presses in a loop until the user presses enter
       // (this might need to be a bit more sophisticated - what about escape?)
       ConsoleKeyInfo keyInfo = Console.ReadKey(true);
       while (keyInfo.Key != ConsoleKey.Enter)
       {
    
           switch (keyInfo.Key)
           {
                case ConsoleKey.LeftArrow:
                        ...
                  // process the left key by moving the cursor position
                  // need to keep track of the position in the buffer
    
             // if the user presses another key then update the text in our buffer
             // and draw the character on the screen
    
             // there are lots of cases that would need to be processed (backspace, delete etc)
           }
           keyInfo = Console.ReadKey(true);
       }
    

    This is quite involved - you'll have to keep ensure the cursor doesn't go out of range and manually update your buffer.