Home > database >  Loop that runs until certain key is pressed - C#
Loop that runs until certain key is pressed - C#

Time:07-27

I'm trying to make a loop that runs until a certain key is pressed without breaking. I'm making a C# console app with .NET 6.0.

What I am aiming for is a loop that continuously until a certain key is pressed. This first example is what I've been using. This loop listens for the key 'L' to be pressed while the key pressed isn't 'B'. However, if a different key is pressed, say 'm', the loop becomes unresponsive and does not do anything when key 'L' or 'B' is pressed afterwards

Example 1 (source)

 do {
       if (key == ConsoleKey.L)
       {
          // Do stuff
       }
 } while (key != ConsoleKey.B);

 // Do stuff after the 'B' key is pressed

In this second example I tried, the loop is unresponsive to any form of input.

Example 2 (source)

while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.L))   
{
    if (Console.ReadKey(true).Key == ConsoleKey.N) 
    {
        // Do stuff
    }
}

// Do stuff when the key 'L' is pressed

Is there a fairly simple fix in which I can have a loop which runs until a certain key is pressed, without breaking when a different key is pressed?

CodePudding user response:

I wrote the solutions in static functions to be more clear.

You could use two different solutions, either use a switch statement that check the key pressed:

`
        static void Solution1()
        {
            while (!(Console.KeyAvailable))
            {
                switch (Console.ReadKey(true).Key)
                {
                    case ConsoleKey.L: Console.WriteLine("L pressed"); break;
                    case ConsoleKey.N: Console.WriteLine("N pressed"); break;
                }
            }
        }
`

Or do a while loop that breaks if your key is pressed, without use a break statement (you can name "conK" variable what you want) :

    static void Solution2()
    {
        ConsoleKey conK = Console.ReadKey(true).Key;
        while (!Console.KeyAvailable && conK != ConsoleKey.L)
        {
            if (conK == ConsoleKey.N) Console.WriteLine("N pressed.");  // Do stuff if N is pressed
            conK = Console.ReadKey(true).Key;
        }
        Console.WriteLine("Loop broke, L pressed."); // Do stuff after L is pressed and loop broke
    }

I tested both before posting, but I'm sure that the second solution is what you're looking for.

Have a nice day !

  • Related