简体   繁体   English

循环运行直到按下某个键 - C#

[英]Loop that runs until certain key is pressed - C#

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.我正在使用 .NET 6.0 制作 C# 控制台应用程序。

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'.此循环侦听要按下的键“L”,而按下的键不是“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但是,如果按下不同的键,比如“m”,则循环变得无响应,并且在之后按下键“L”或“B”时不会执行任何操作

Example 1 ( source )示例 1(来源

 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 )示例 2( 来源

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?是否有一个相当简单的修复方法,我可以在其中运行一个循环,直到按下某个键,而在按下另一个键时不会中断?

I wrote the solutions in static functions to be more clear.为了更清楚,我在 static 函数中写了解决方案。

You could use two different solutions, either use a switch statement that check the key pressed:您可以使用两种不同的解决方案,或者使用 switch 语句来检查按下的键:

`
        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):或者做一个while循环,如果你的键被按下就会中断,而不使用break语句(你可以命名你想要的“conK”变量):

    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祝你今天过得愉快

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM