C# - How to Stop a Loop When a Key is Pressed? [duplicate]

Deadly 提交于 2021-01-01 04:33:46

问题


Currently I am using this code:

using System;

namespace Project
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            bool key = false;
            while (key == false)
            {
                Console.WriteLine ("Loop");
            }
        }
    }
}

Which works fine, but I wanted to make the loop stop when a key is pressed. I tried this:

using System;

namespace Project
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            bool key = false;
            while (key == false)
            {
                Console.WriteLine ("Loop");
                {
                Console.ReadKey (true);
                key = true
                }
            }
        }
    }
}

But that just continues the loop when a key is pressed. Any solutions?


回答1:


I suggest using Console.KeyAvailable:

 while (!Console.KeyAvailable) {
   Console.WriteLine("Loop");
 }


来源:https://stackoverflow.com/questions/41542248/c-sharp-how-to-stop-a-loop-when-a-key-is-pressed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!