我可以在C#Console应用程序中创建一个循环并监听按键,然后将该键值传递给变量,而不停止循环吗

我可以在C#Console应用程序中创建一个循环并监听按键,然后将该键值传递给变量,而不停止循环吗,c#,.net,C#,.net,例如,此代码: while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)) { //do something } 但是当按下键而不是停止时,我只得到一个变量的键值返回一个实例。因此,您可以将Console.ReadKey(bool)的结果存储在ConsoleKeyInfo类型的变量中,并使用内部while循环等待按键 ConsoleKeyInfo cki;

例如,此代码:

    while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
{
     //do something
}
但是当按下键而不是停止时,我只得到一个变量的键值

返回一个实例。因此,您可以将
Console.ReadKey(bool)
的结果存储在
ConsoleKeyInfo
类型的变量中,并使用内部
while
循环等待按键

ConsoleKeyInfo cki;

do
{
   while (!Console.KeyAvailable)
   {
      // Listening for a keypress...
   }

   cki = Console.ReadKey(true);
   // Do something with cki.
} while (cki.Key != ConsoleKey.Escape);

如果要继续循环,请将
KeyAvailable
从while条件中移除

while (true)
{
    if (Console.KeyAvailable) 
    {
        var key = Console.ReadKey(true);
        if (key.Key == ConsoleKey.Escape) break;
    }
    //Do other stuff
}

这是另一个可能对您有所帮助的示例

        ConsoleKeyInfo key = new ConsoleKeyInfo();
        Console.Write("type some characters (ESC to quit)> ");

        while (true)
        {
            key = Console.ReadKey(intercept: true); // use false to allow the characters to display
            
            if(key.Key == ConsoleKey.Escape)
            {
                Console.WriteLine();
                Console.WriteLine("You pressed ESC. The program will terminate when you press the ENTER key.");
                Console.ReadLine();
                return;
            }  
            
            // do some more stuff with the key value from the key press if you want to now
        }

如果你不想循环结束,为什么要把它放在循环条件下?@Xerilio我把它放在这里只是为了举例说明我想做的事情,我尝试了其他方法,但我只是让代码工作得非常完美,我尝试过做类似的事情,但它只是恶化了,谢谢你