简体   繁体   中英

How to print when the key is pressed, it will print something and if not it will print another thing

As the title implies, I want to print the "Outside loop" words when the user doesn't press anything from their keyboard. In the other side, if the user press the Enter button it will print "inside loop" words and break it to end the loop. However, in the end, if the user didn't press anything, the programs will run nothing and when the user press the Enter it will print both words simultaneously.

 while(true)
 {
   if (Console.ReadKey(true).Key == ConsoleKey.Enter)
   {
      Console.WriteLine( "inside loop");
      break;
   }
      Console.WriteLine("outside loop");
 }

Current Result : 结果

Try this, this will look if a key is pressed and if its the enter key:

while (true)
{
    if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Enter)
    {
            Console.WriteLine("inside loop");
            break;
    }
                
    Console.WriteLine("outside loop");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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