没有按下按键时,ReadKey会执行某些操作

use*_*135 5 c# console console-application console.readkey readkey

我试图运行我的代码直到Esc被按下.因此我ReadKey在我的控制台中使用

var input = Console.ReadKey();
do
{

} while (input.Key != ConsoleKey.Escape);
Run Code Online (Sandbox Code Playgroud)

但是在"ConsoleKey"它说,在'bool'中不可能使用ConsoleKey.我该如何解决这个问题?或者我应该使用什么呢?

Kev*_*ühl 9

试试这个:

ConsoleKeyInfo input;
do
{
    input = Console.ReadKey();
} while (input.Key != ConsoleKey.Escape);
Run Code Online (Sandbox Code Playgroud)


Eri*_*rik 5

您是否有特殊原因要使用ESC密钥而不是传统的CTRL+ C

您可以Console.CancelKeyPress为后者挂钩事件,它在命令行界面世界中是标准的.

Console.ReadKey()阻塞,这在一些循环中可能会有问题.我们来看这个例子:

    using System.Threading;
    using System.Threading.Tasks;

    CancellationTokenSource cts;

    public void Run()
    {
        cts = new CancellationTokenSource();
        var task = new Task(DoSomething, cts.Token);

        task.Start();

        while (!task.IsCompleted)
        {
            var keyInput = Console.ReadKey(true);

            if (keyInput.Key == ConsoleKey.Escape)
            {
                Console.WriteLine("Escape was pressed, cancelling...");
                cts.Cancel();
            }
        }

        Console.WriteLine("Done.");
    }

    void DoSomething()
    {
        var count = 0;

        while (!cts.IsCancellationRequested)
        {
            Thread.Sleep(1000);
            count++;

            Console.WriteLine("Background task has ticked ({0}).", count.ToString());
        }
    }
Run Code Online (Sandbox Code Playgroud)

这将使用a进行一些后台工作Task,同时等待ESC按下.取消工作正常,但Console.ReadKey()在完成(取消)后将再次停留.

您可以使用Win32 API等,GetKeyboardState并检查密钥代码,因为它没有阻止.但是,我建议CancelKeyPress改为使用该事件(CTRL+ C):

    void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
    {
        Console.WriteLine("Cancelling...");
        cts.Cancel();

        e.Cancel = true;    // Do not terminate immediately!
    }
Run Code Online (Sandbox Code Playgroud)