在输出到控制台应用程序时检测Keypress

时间:2016-04-08 23:59:31

标签: c#

也许我正在以错误的方式看待这个问题,但我希望能够不断地输出到控制台应用程序,作为一个正在运行的日志,但允许用户按Escape之类的东西来停止操作。我尝试了一些涉及ReadKey和KeyAvailable的东西,但我认为它们并不适用于我正在寻找的东西。可能是一个简单的问题,但任何帮助都表示赞赏。

3 个答案:

答案 0 :(得分:0)

试试这个:

do {
    while (! Console.KeyAvailable) {
        // your code
    }       
} while (Console.ReadKey(true).Key != ConsoleKey.Escape); //any key that you want to look for);

答案 1 :(得分:0)

您可以使用Console.KeyAvailable

Console.WriteLine("ESC will stop");
do {
    while (!Console.KeyAvailable) {
        // do what you want here
   }       
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);

答案 2 :(得分:0)

在不了解您的架构的情况下,我建议将worker(生成输出)和检查分成不同的线程。这样您就不必混合输出代码并检查程序退出。

这是你的工作人员:

class Worker {
    public bool shoudstop {get; set;}
    public bool isrunning {get; set;}

    //....

    public void DoWork() {
        isrunning = true;
        shouldstop = false;
        while (!shouldstop) {
            //do your business logic here
            Console.WriteLine("hello world ...");
        }
        isrunning = false;
    }
    // ...
}

在主线程中,您可以永久检查是否按下了转义键。

//start your worker in a new thread
Worker worker = new Worker();
(new Thread(() => {worker.DoWork(); }).Start();


//Wait, until ESC is pressed
while (true) {
    if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) break;
    Thread.Sleep(100);
}

//Signal the worker thread to stop, and wait until it's finished
worker.shouldstop = true;
while (worker.isrunning) Thread.Sleep(10);