Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 962
Ben Cameron Avatar asked Sep 05 '25 03:09

Ben Cameron


1 Answers

I suggest using Console.KeyAvailable:

 while (!Console.KeyAvailable) {
   Console.WriteLine("Loop");
 }
like image 69
Dmitry Bychenko Avatar answered Sep 07 '25 22:09

Dmitry Bychenko