2017-04-22 61 views
0

我无法弄清楚如何字这个问题......按键排列队列吗?

在我的应用程序,如果用户按下甚至分配到Console.ReadKey(在该ConsoleKeyInfo对象之前进入),它会自动将其设置为任何的用户按下。实际上,它似乎是堆叠的,因为如果用户输入5次,它会自动分配5次,这对我来说是非常糟糕的。我已经非常仔细地通过调试过程了解了这一点,我相当确信这将发生。使用Thread.Sleep()创建用户可以多次按Enter的机会窗口。我被警告不要使用它,但我认为这对我来说很好,因为我需要一切停止一会儿,以便用户可以阅读一行文本。我在想也许这样的机会预计不会存在?或者,也许我错误地解释了这里发生了什么?我只需要在整个应用程序的一行代码中输入...

回答

0

如果我正在阅读你说的正确的话,你不喜欢按下按键时所有排队的方式,然后只有当你做Console.Readkey ....时会被删除,并且当你重复接近时会引起你的问题。

以下是尝试按照可能有所帮助的方式处理按键队列 - 根据需要对其进行调整。我不知道你是否只是使用键盘进行“选项”选择,或对于自由文本输入等,但我认为它可以提供帮助。

到这里看看:

我已经适应,如此,它会尝试检测“重复”按键,它会“忽略他们” /“吃”如果它们在一定的时间范围内一起发生......但会继续前进,如果它是不同的按键。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 

namespace ConsoleApp6 
{ 
    class Program 
    { 
     public static void Main() 
     { 
      ConsoleKeyInfo ckilast = default(ConsoleKeyInfo); 
      ConsoleKeyInfo ckicurrent = default(ConsoleKeyInfo); 

      Console.WriteLine("\nPress a key to display; press the 'x' key to quit."); 

      // Adjust this "window" period, till it feels right 

      //TimeSpan tsignorerepeatedkeypresstimeperiod = new TimeSpan(0, 0, 0, 0, 0); // 0 for no extra delay 

      TimeSpan tsignorerepeatedkeypresstimeperiod = new TimeSpan(0, 0, 0, 0, 250); 

      do 
      { 
       while (Console.KeyAvailable == false) 
        Thread.Sleep(250); // Loop until input is entered. 

       ckilast = default(ConsoleKeyInfo); 

       DateTime eatingendtime = DateTime.UtcNow.Add(tsignorerepeatedkeypresstimeperiod); // will ignore any "repeated" keypresses of the same key in the repeat window 

       do 
       { 
        while (Console.KeyAvailable == true) 
        { 
         ckicurrent = Console.ReadKey(true); 

         if (ckicurrent.Key == ConsoleKey.X) 
          break; 

         if (ckicurrent != ckilast) // different key has been pressed to last time, so let it get handled 
         { 
          eatingendtime = DateTime.UtcNow.Add(tsignorerepeatedkeypresstimeperiod); // reset window period 

          Console.WriteLine("You pressed the '{0}' key.", ckicurrent.Key); 

          ckilast = ckicurrent; 

          continue; 
         } 
        } 

        if (Console.KeyAvailable == false) 
        { 
         Thread.Sleep(50); 
        } 

       } while (DateTime.UtcNow < eatingendtime); 

      } while (ckicurrent.Key != ConsoleKey.X); 
     } 
    } 
}