Listen for key press in .NET console app

后端 未结 9 1337
隐瞒了意图╮
隐瞒了意图╮ 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:17

    Here is an approach for you to do something on a different thread and start listening to the key pressed in a different thread. And the Console will stop its processing when your actual process ends or the user terminates the process by pressing Esc key.

    class SplitAnalyser
    {
        public static bool stopProcessor = false;
        public static bool Terminate = false;
    
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Split Analyser starts");
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Press Esc to quit.....");
            Thread MainThread = new Thread(new ThreadStart(startProcess));
            Thread ConsoleKeyListener = new Thread(new ThreadStart(ListerKeyBoardEvent));
            MainThread.Name = "Processor";
            ConsoleKeyListener.Name = "KeyListener";
            MainThread.Start();
            ConsoleKeyListener.Start();
    
            while (true) 
            {
                if (Terminate)
                {
                    Console.WriteLine("Terminating Process...");
                    MainThread.Abort();
                    ConsoleKeyListener.Abort();
                    Thread.Sleep(2000);
                    Thread.CurrentThread.Abort();
                    return;
                }
    
                if (stopProcessor)
                {
                    Console.WriteLine("Ending Process...");
                    MainThread.Abort();
                    ConsoleKeyListener.Abort();
                    Thread.Sleep(2000);
                    Thread.CurrentThread.Abort();
                    return;
                }
            } 
        }
    
        public static void ListerKeyBoardEvent()
        {
            do
            {
                if (Console.ReadKey(true).Key == ConsoleKey.Escape)
                {
                    Terminate = true;
                }
            } while (true); 
        }
    
        public static void startProcess()
        {
            int i = 0;
            while (true)
            {
                if (!stopProcessor && !Terminate)
                {
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("Processing...." + i++);
                    Thread.Sleep(3000);
                }
                if(i==10)
                    stopProcessor = true;
    
            }
        }
    
    }
    

提交回复
热议问题