Listen for key press in .NET console app

后端 未结 9 1455
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 05:02

How can I continue to run my console application until a key press (like Esc is pressed?)

I\'m assuming its wrapped around a while loop. I don\'t like

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 05:21

    with below code you can listen SpaceBar pressing , in middle of your console execution and pause until another key is pressed and also listen for EscapeKey for breaking the main loop

    static ConsoleKeyInfo cki = new ConsoleKeyInfo();
    
    
    while(true) {
          if (WaitOrBreak()) break;
          //your main code
    }
    
     private static bool WaitOrBreak(){
            if (Console.KeyAvailable) cki = Console.ReadKey(true);
            if (cki.Key == ConsoleKey.Spacebar)
            {
                Console.Write("waiting..");
                while (Console.KeyAvailable == false)
                {
                    Thread.Sleep(250);Console.Write(".");
                }
                Console.WriteLine();
                Console.ReadKey(true);
                cki = new ConsoleKeyInfo();
            }
            if (cki.Key == ConsoleKey.Escape) return true;
            return false;
        }
    

提交回复
热议问题