好吧,问题的标题可能有点不对劲,但我没有想到更好的,所以这里是:
我想阅读用户输入的“到目前为止”的内容,我需要它像这样工作:用户输入一些所需的数据,然后询问他/她是否想要完整的进度输出或只是结果。
当然,我可以调用 ReadLine 并查看他/她写了什么,但我希望它更整洁 - 在最终数据输入后,他/她会被要求提供详细信息。程序会等待大约 2 秒,然后“读取”用户写的内容。如果什么都没有,程序会正常运行,如果需要字符串,程序会提供详细的计算。
我希望它是清楚的
感谢您的解答
E:另一种方法是模拟enter在那 2 秒后按下按键,所以这个或那个都很好。
ANSWER对于任何对工作代码感兴趣的人。
bool timepassed = false;
bool detailmode = false;
long start = System.Environment.TickCount;
while (Console.KeyAvailable == false) // This loop will quit when KeyAvailable is true, i.e. a key is pressed (OR by the break command below)
{
Console.Write("."); // write dot every 100ms to indicate progress
System.Threading.Thread.Sleep(100);
if (System.Environment.TickCount - start > 1250){
timepassed=true; // if more than 1250ms passed, set flag break
break;
}
}
detailmode = !timepassed; // if time didnt pass, then user did press a key (and vice versa)->set detailmode
if (detailmode == true)
{
Console.ReadKey(true); // hide the pressed key
Console.WriteLine("\n\n-Detailni mod-"); // notify user about detailed mode
}
看看这两篇文章:
- 控制台中的 KeyDown 事件
- KeyAvailable 属性
特别是,MSDN 文章中有这样的例子:
class Sample
{
public static void Main()
{
ConsoleKeyInfo cki = new ConsoleKeyInfo();
do {
Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");
// Your code could perform some useful task in the following loop. However,
// for the sake of this example we'll merely pause for a quarter second.
while (Console.KeyAvailable == false)
Thread.Sleep(250); // Loop until input is entered.
cki = Console.ReadKey(true);
Console.WriteLine("You pressed the '{0}' key.", cki.Key);
} while(cki.Key != ConsoleKey.X);
}
}
EDIT- 根据您实际对输入执行的操作,您可能希望将其累积在缓冲区中或StringBuilder
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)