C# .NET 控制台应用程序获取键盘输入

C# .NET Console Application getting keyboard input

我正在尝试制作一个控制台应用程序,它(不要问我为什么)需要键盘输入(向下箭头和向上箭头)。到目前为止,一切都很好。键盘输入需要永远处于 While(true) 循环和 运行 中,并使用 if 语句进行检查。我尝试使用 Console.ReadKey() == ConsoleKey.UpArrow; 但这似乎暂停了 运行ning 的循环。无论如何,我可以 运行 一个 if(Keyboard.input == Key.UpArrow){} 语句而不暂停循环(如果不是这种情况,基本上跳过它)?

这是我的意思的一个例子:

while (true){

if (Console.ReadKey() == ConsoleKey.UpArrow){ // this pauses the loop until input, which is not what I want / need.
 // Do stuff
}
Frame.Update();
}

Console.ReadKey 锁定线程。您应该创建另一个线程并在那里读取密钥。 此处示例:

Task.Factory.StartNew(() =>
            {
                if (Console.ReadKey().Key == ConsoleKey.UpArrow)
                {
                    Console.WriteLine("Pressed");
                }
            });

诀窍是首先需要检查缓存中是否有KeyAvailable,然后然后使用ReadKey()读取它。之后,您的代码应该会按预期工作。执行此操作的代码行类似于:

// Check if there's a key available. If not, just continue to wait.
if (Console.KeyAvailable) { var key = Console.ReadKey(); }

这里有一个示例来演示:

public static void Main(string[] args)
{
    Console.SetCursorPosition(Console.WindowWidth / 2, Console.WindowHeight / 2);
    Console.CursorVisible = false;
    Console.Write('*');

    var random = new Random();

    while (true)
    {
        if (Console.KeyAvailable)
        {
            var key = Console.ReadKey(true);

            switch (key.Key)
            {
                case ConsoleKey.UpArrow:
                    if (Console.CursorTop > 0)
                    {
                        Console.SetCursorPosition(Console.CursorLeft - 1, 
                            Console.CursorTop - 1);
                        Console.Write('*');
                    }
                    break;
                case ConsoleKey.DownArrow:
                    if (Console.CursorTop < Console.BufferHeight)
                    {
                        Console.SetCursorPosition(Console.CursorLeft - 1, 
                            Console.CursorTop + 1);
                        Console.Write('*');
                    }
                    break;
                case ConsoleKey.LeftArrow:
                    if (Console.CursorLeft > 1)
                    {
                        Console.SetCursorPosition(Console.CursorLeft - 2, 
                            Console.CursorTop);
                        Console.Write('*');
                    }
                    break;
                case ConsoleKey.RightArrow:
                    if (Console.CursorLeft < Console.WindowWidth - 1)
                    {
                        Console.Write('*');
                    }
                    break;
            }
        }

        // This method should be called on every iteration, 
        // and the iterations should not wait for a key to be pressed
        // Instead of Frame.Update(), change the foreground color every three seconds  
        if (DateTime.Now.Second % 3 == 0) 
            Console.ForegroundColor = (ConsoleColor) random.Next(0, 16);
    }
}