一种稍微不同的方法是使用Stopwatch 类来测量时间,并且只有在我们通过了指定的“闪烁间隔”时才更改文本。
我们可以编写一个方法来执行此操作,它需要一个 string prompt 来显示,一个 TimeSpan interval 指定在闪烁文本之间等待多长时间。
在代码中,我们将捕获光标位置和控制台颜色,启动秒表,然后每次秒表经过interval 指定的时间量时,我们将交换Console.ForegroundColor 和Console.BackgroundColor。
该方法将执行此操作,直到用户按下一个键,我们将返回给调用者:
private static ConsoleKey FlashPrompt(string prompt, TimeSpan interval)
{
// Capture the cursor position and console colors
var cursorTop = Console.CursorTop;
var colorOne = Console.ForegroundColor;
var colorTwo = Console.BackgroundColor;
// Use a stopwatch to measure time interval
var stopwach = Stopwatch.StartNew();
var lastValue = TimeSpan.Zero;
// Write the initial prompt
Console.Write(prompt);
while (!Console.KeyAvailable)
{
var currentValue = stopwach.Elapsed;
// Only update text with new color if it's time to change the color
if (currentValue - lastValue < interval) continue;
// Capture the current value, swap the colors, and re-write our prompt
lastValue = currentValue;
Console.ForegroundColor = Console.ForegroundColor == colorOne
? colorTwo : colorOne;
Console.BackgroundColor = Console.BackgroundColor == colorOne
? colorTwo : colorOne;
Console.SetCursorPosition(0, cursorTop);
Console.Write(prompt);
}
// Reset colors to where they were when this method was called
Console.ForegroundColor = colorOne;
Console.BackgroundColor = colorTwo;
return Console.ReadKey(true).Key;
}
现在,在调用方,我们将向其传递文本“按转义键继续”和我们想要等待的时间量(在您的情况下为TimeSpan.FromMilliseconds(500)),然后我们可以无限地调用它@ 987654329@循环,直到用户按下ConsoleKey.Escape:
private static void Main()
{
// Flash prompt until user presses escape
while (FlashPrompt("Press escape to continue...",
TimeSpan.FromMilliseconds(500)) != ConsoleKey.Escape) ;
// Code execution continues after they press escape...
}
这里的好处是您可以重复使用逻辑并可以指定更短或更长的闪存时间。您还可以通过在调用方法之前指定它们来更改“闪烁”的颜色(或者可以编写方法以将它们作为参数)。
例如,试试这个:
private static void Main()
{
Console.WriteLine("Hello! The text below will flash red " +
"and green once per second until you press [Enter]");
Console.ForegroundColor = ConsoleColor.Red;
Console.BackgroundColor = ConsoleColor.Green;
while (FlashPrompt("Press [Enter] to continue...",
TimeSpan.FromSeconds(1)) != ConsoleKey.Enter) ;
Console.ResetColor();
// Code will now continue in the original colors
}