简体   繁体   English

C# 程序不会继续,直到按键被按下

[英]C# Program won't proceed until key is pressed

I'm trying to make a program that prints number in a loop, but when "X" is pressed the program should stop (in theory).我正在尝试制作一个循环打印数字的程序,但是当按下“X”时,程序应该停止(理论上)。

It isn't working until a button is pressed.在按下按钮之前它不起作用。 When i hold any button it gets in a loop but the loop should start with the beggining.当我按住任何按钮时,它会进入一个循环,但循环应该从开始开始。

Code:代码:

static void Main(string[] args)
    {
        Random rnd = new Random();
        string[] k = { "1", "2", "3", "4", "5", "6" };
        while (true)
        {
            Console.WriteLine(k[rnd.Next(1, 6)]);
            if (Console.ReadKey(true).Key == ConsoleKey.X)
            {
                break; 
            }
        }
        Console.ReadKey();

    }

Only read a key when there is one pressed:仅在按下一个键时读取一个键:

//if (Console.ReadKey(true).Key == ConsoleKey.X)
  if (Console.KeyAvailable && ReadKey(true).Key == ConsoleKey.X)

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

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