ReadKey需要输入两次

时间:2014-03-12 19:12:41

标签: c# console-application

public static void readkey()
{
    ConsoleKeyInfo input = Console.ReadKey();

    switch(input.Key)
    {
        case ConsoleKey.D9:
             Console.Clear();
             Console.WriteLine("U heeft het programma succesvol afgesloten!");
             Console.Read();
             Environment.Exit(0);
        break;

        case ConsoleKey.D1:
             overzichtmp();
        break;

        case ConsoleKey.D2:
             overzichtvr();
        break;

        default:
        {
            Console.Clear();
            Console.WriteLine("Voer een geldig nummer in!");
            Console.Read();
            showmenu();
            break;
        }
    }
}

如果我第一次按下某个键然后直接返回该方法并且第二次它刚刚开始正常,任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我不确定下面是否是您正在寻找的内容,但它会设置程序循环以调用您的读取密钥并取消第二个Console.Read并将其替换为睡眠等待。

static void Main(string[] args)
{
    while (true)
    {
        readkey();
    }
}

public static void readkey()
{
    ConsoleKeyInfo input = Console.ReadKey();

    switch(input.Key)
    {
        case ConsoleKey.D9:
             Console.Clear();
             Console.WriteLine("U heeft het programma succesvol afgesloten!");
             //You might want to wait:  System.Threading.Thread.Sleep(5000);
             Environment.Exit(0);
        break;

        case ConsoleKey.D1:
             overzichtmp();
        break;

        case ConsoleKey.D2:
             overzichtvr();
        break;

        default:
        {
            Console.Clear();
            Console.WriteLine("Voer een geldig nummer in!");
            // possibly add the wait here as well
            showmenu();
            break;
        }
    }
}