Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# console: How to ReadLine without the need of pressing [Enter]

My c# console application is used as a login for my c# form application, the problem is, in my c# console app i haven't been able to figure out a way to ReadLine without the need of pressing Enter because i need to detect whether F2 or Enter is pressed then ReadLine without needing user to press Enter again. For example, if i wanted to detect if F2 is pressed i would need to wait until F2 is pressed until I'm able to ReadLine, Hopefully this question was worded in a way that it makes sense, I'm sure you can tell I'm quite a 'noob' at c#.
Example of my problem:

static void Main()
{
    var KP = Console.ReadKey();
    if (KP.Key == ConsoleKey.F2)
    {                                    
        //User Presses F2                
    }      
    else if (KP.Key == ConsoleKey.Enter)
    {
        string UserName = ReadLineWithoutPressingEnter();//Just a example
        //ReadLine without needing to press enter again
    }                            
}                         




Thank you for your time.

like image 702
C0d1ng Avatar asked May 20 '16 19:05

C0d1ng


2 Answers

Save the result from ReadKey and then just do a ReadLine:

   public static void Main(string[] args)
    {
        var KP = Console.ReadKey();
        if (KP.Key == ConsoleKey.F2)
        {
            return;               
        }

        string UserName = KP.KeyChar + Console.ReadLine();

        Console.WriteLine(UserName);
        Console.ReadLine();
    }
like image 108
Jeff Hornby Avatar answered Sep 18 '22 14:09

Jeff Hornby


You've already found Console.ReadKey(). That's a start. You'll need to also build a state machine around this function to return a completed string at the end of the line, but this method is the key to making that work. Don't forget to handle things like backspace and delete.

like image 27
Joel Coehoorn Avatar answered Sep 19 '22 14:09

Joel Coehoorn