如何读取用户写的内容(不按回车键)- c#控制台
本文关键字:回车 控制台 何读取 读取 用户 | 更新日期: 2023-09-27 18:18:12
这个问题的标题可能有点不合适,但我没有找到更好的,所以它是这样的:
我想读什么用户输入'到目前为止',我需要它这样工作:用户输入一些所需的数据,然后被问到他/她是否想要完整的进度输出或只是结果。
当然,我可以调用ReadLine,看看他/她写了什么,但我希望它更整洁-在最终数据输入后,他/她将被要求提供详细信息。程序会等待大约2秒,然后"读取"用户所写的内容。如果没有,程序将正常运行,如果需要字符串,程序将提供详细的计算。
我希望你明白
谢谢你的回答
E:另一种方法是在2秒后模拟输入键,所以这样或那样都很好。
对于任何对工作代码感兴趣的人。
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属性/gh>
特别地,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
中。
我怀疑您正在寻找ReadKey
方法:
您需要依次处理每个按键,并在用户最终按enter键时自己重新构建整个命令。
编辑:
如果你想在一段时间后超时,看看这个问题的解决方案:如何在Console.ReadLine()中添加超时?
我原来误解了你的意思。
ConsoleKeyInfo cki = Console.ReadKey();
Console.WriteLine(cki.Key.ToString());