簡體   English   中英

沒有按下按鍵時,ReadKey會執行某些操作

[英]ReadKey while key is not pressed do something

我試圖運行我的代碼,直到Esc被按下。 因此我在控制台中使用ReadKey

var input = Console.ReadKey();
do
{

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

但是在“ConsoleKey”它說,在'bool'中不可能使用ConsoleKey。 我該如何解決這個問題? 或者我應該使用什么呢?

試試這個:

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

是否有特殊原因要使用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());
        }
    }

這將使用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!
    }
ConsoleKeyInfo input;
do
{
    input = Console.ReadKey();
} while (input.Key != ConsoleKey.Escape);

或更短

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM