c# – 当用户按下escape时,如何“暂停”控制台应用程序?

c# – 当用户按下escape时,如何“暂停”控制台应用程序?,第1张

概述我正在创建一个将执行无限过程的C#控制台应用程序.当用户按下转义键时,如何让应用程序暂停”? 一旦用户按下转义键,我想要选择退出应用程序或继续循环它停止的位置.我不希望在这个过程中出现任何不连续性.如果我在步骤100按Esc,我应该能够在步骤101正确选择. 到目前为止,这是我的方法: // Runs the infinite loop application public stati @H_404_1@我正在创建一个将执行无限过程的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,因此它不会暂停以等待输入.如果条件为真,您可以检查是否按下了转义键并暂停或执行任何 *** 作.

总结

以上是内存溢出为你收集整理的c# – 当用户按下escape时,如何“暂停”控制台应用程序?全部内容,希望文章能够帮你解决c# – 当用户按下escape时,如何“暂停”控制台应用程序?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1263272.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存