好吧,问题的标题可能有点不对劲,但我没有想出更好的办法,所以就这样吧:
我想阅读用户输入“到目前为止”的内容,我需要它像这样工作:用户输入一些必需的数据,然后被询问他/她是否想要完整的进度输出或只是结果。
当然,我可以调用 ReadLine 看看他/她写了什么,但我想让它更整洁——在最后的数据输入之后,他/她会被要求提供详细信息。该程序将等待 2 秒,然后“读取”用户写的内容。如果没有,程序会正常运行,如果需要字符串,程序会提供详细的计算。
我希望这是清楚的
感谢解答
E:另一种方法是在 2 秒后模拟 enter 按键,所以这个或那个都不错。
回答 对于任何对工作代码感兴趣的人。
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
}
最佳答案
看看这两篇文章:
特别是,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);
}
}
编辑 - 根据您对输入的实际操作,您可能希望将其累积在缓冲区或 StringBuilder
中。
关于c# - 如何阅读用户写的内容(无需按回车键)- 控制台 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8564090/