简体   繁体   English

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

[英]ReadKey while key is not pressed do something

I am trying to run my code until Esc was pressed. 我试图运行我的代码,直到Esc被按下。 Therefore I am using ReadKey in my Console 因此我在控制台中使用ReadKey

var input = Console.ReadKey();
do
{

} while (input.Key != ConsoleKey.Escape);

but at "ConsoleKey" it says that, ConsoleKey isn't possible in 'bool'. 但是在“ConsoleKey”它说,在'bool'中不可能使用ConsoleKey。 How can I fix that? 我该如何解决这个问题? Or what shall I use instead? 或者我应该使用什么呢?

Try this: 试试这个:

ConsoleKeyInfo input;
do
{
    input = Console.ReadKey();
} while (input.Key != ConsoleKey.Escape);

Is there a particular reason you want to use the ESC key instead of the conventional CTRL + C ? 是否有特殊原因要使用ESC键而不是传统的CTRL + C

You can hook into the Console.CancelKeyPress event for the latter and it is standard in the command-line interface world. 您可以为后者挂接Console.CancelKeyPress事件,它在命令行界面世界中是标准的。

Console.ReadKey() is blocking, which can be problematic in some loops. Console.ReadKey()是阻塞的,在某些循环中可能会出现问题。 Let's take this example: 我们来看这个例子:

    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());
        }
    }

This will do some background work using a Task , while waiting for ESC to be pressed. 这将使用Task执行一些后台工作,同时等待按下ESC Cancellation works just fine, however it will be stuck at the Console.ReadKey() one more time after completion (cancellation). 取消工作正常,但在完成(取消)后它将再次停留在Console.ReadKey() )上。

You could use Win32 API such as GetKeyboardState and check the key codes instead, since it is not blocking. 您可以使用Win32 API,例如GetKeyboardState并检查密钥代码,因为它没有阻塞。 However, I recommend using the CancelKeyPress event instead ( CTRL + C ): 但是,我建议使用CancelKeyPress事件( CTRL + C ):

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

        e.Cancel = true;    // Do not terminate immediately!
    }
ConsoleKeyInfo input;
do
{
    input = Console.ReadKey();
} while (input.Key != ConsoleKey.Escape);

or shorter 或更短

while (Console.ReadKey().Key != ConsoleKey.Escape){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM