c# 控制台:如何在不需要按 [Enter] 的情况下读取行

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

我的 C# 控制台应用程序用作我的 C# 表单应用程序的登录,问题是,在我的 C# 控制台应用程序中,我无法找到一种方法来 ReadLine 而无需按下 Enter 因为我需要检测是否按下了 F2Enter 然后 ReadLine 不需要用户再次按下 Enter。例如,如果我想检测 F2 是否被按下,我需要等到 F2 被按下,直到我能够 ReadLine,希望这个问题的措辞方式这是有道理的,我相信你可以看出我在 c# 方面非常 'noob'。
我的问题示例:

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
    }                            
}                         




感谢您的宝贵时间。

您已经找到 Console.ReadKey()。这是一个开始。您还需要围绕此函数构建一个状态机,以在行尾 return 一个完整的字符串,但此方法是实现该功能的关键。不要忘记处理退格和删除之类的事情。

保存 ReadKey 的结果,然后执行 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();
    }

这是一个例子试试这个

   static void Main(string[] args)
    {
        ConsoleKeyInfo cki = new ConsoleKeyInfo();
        int i = 0;
        do
        {


            while (Console.KeyAvailable == false)
                Thread.Sleep(250); // Loop until input is entered.
            cki = Console.ReadKey(true);

            if (cki.Key == ConsoleKey.F1)
            {
                Console.WriteLine("User Have Press F1");
                //do some thing
            }

            if (cki.Key == ConsoleKey.Enter)
            {
                Console.WriteLine("User Have Press Enter");
                //do some thing
            }
            if (cki.Key == ConsoleKey.A)
            {
                Console.WriteLine("User Have Press A");
                //do some thing
            }

        } while (cki.Key != ConsoleKey.X);
    }

这应该有效

    static void Main(string[] args)
    {
        ConsoleKeyInfo e;
        string userName = "";

        while (true)
        {
            e = Console.ReadKey();

            if (e.Key == ConsoleKey.Enter)
            {
                break;
            }
            else if (e.Key == ConsoleKey.F2)
            {
                //things to do when F2
            }

            userName += e.KeyChar;
        }

        Console.WriteLine("username: " + userName);
        Console.Read();
    }