当用户按Esc键时,如何暂停控制台应用程序(&Q;)? [英] How do I "Pause" a console application when the user presses escape?

查看:48
本文介绍了当用户按Esc键时,如何暂停控制台应用程序(&Q;)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个C#控制台应用程序,它将执行无限进程。如何在用户按退出键时使应用程序"暂停"?

一旦用户按下退出键,我希望该选项要么退出应用程序,要么从停止的地方继续循环。我不希望在这个过程中有任何中断。如果我在步骤100按Esc,我应该能够在步骤101立即恢复。

以下是我到目前为止的方法:

    // Runs the infinite loop application 
    public static void runLoop()
    {
        int count = 0;
        while (Console.ReadKey().Key!= ConsoleKey.Escape)
        {
                WriteToConsole("Doing stuff.... Loop#" + count.ToString());
                for (int step = 0; step <= int.MaxValue; step++ ) {
                    WriteToConsole("Performing step #" + step.ToString());
                    if (step == int.MaxValue)
                    {
                        step = 0; // Re-set the loop counter
                    }
                }


                count++;
        }

        WriteToConsole("Do you want to exit?  y/n");
        exitApplication(ReadFromConsole());
    }

有没有办法在单独的线程中检查用户输入键,然后在另一个线程看到Esc按键时暂停无限循环?

推荐答案

若要了解循环中是否有可用的密钥,您可以执行以下操作:

while (someLoopCondition)
{
    //Do lots of work here
    if (Console.KeyAvailable)
    {
        var consoleKey = Console.ReadKey(true);  //true keeps the key from
                                                 //being displayed in the console
        if (consoleKey.Key == ConsoleKey.Escape)
        {
            //Pause here, ask a question, whatever.
        }
    }
}

Console.KeyAvailable如果输入流中有一个键准备读取,并且它是一个非阻塞调用,那么它将返回TRUE,因此它不会暂停等待输入。您可以检查是否按了退出键,如果条件为真,则暂停或执行任何操作。

这篇关于当用户按Esc键时,如何暂停控制台应用程序(&Q;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆