如果我正在閱讀你說的正確的話,你不喜歡按下按鍵時所有排隊的方式,然後只有當你做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);
}
}
}