如果我有一个Console.ReadKey(),它会使整个程序陷入困境,如何才能使它读取1秒的密钥,如果没有读取某个键,则会设置其他一些内容。
发布于 2013-01-17 18:13:28
控制台有一个属性KeyAvailable。但是您想要的功能(超时)不可用。您可以编写自己的函数
private static ConsoleKeyInfo WaitForKey(int ms)
{
int delay = 0;
while (delay < ms) {
if (Console.KeyAvailable) {
return Console.ReadKey();
}
Thread.Sleep(50);
delay += 50;
}
return new ConsoleKeyInfo((char)0, (ConsoleKey)0, false, false, false);
}此函数循环,直到所需的时间(以毫秒为单位)过去或按下一个键。它在调用Console.ReadKey();之前检查密钥是否可用。检查Console.KeyAvailable立即继续,是否有密钥可用。如果已按下键并准备由ReadKey和false读取,则返回false。如果没有可用的键,则函数休眠50 ms,直到执行下一个循环。这比不睡觉的循环更好,因为这将给你100%的CPU使用率(在一个核心上)。
如果您想知道用户按了哪个键,该函数将像ConsoleKeyInfo一样返回一个ReadKey。最后一行创建一个空的ConsoleKeyInfo (参见ConsoleKeyInfo结构和ConsoleKeyInfo构造器)。它允许您测试用户是否按下了键,或者函数是否超时。
if (WaitForKey(1000).KeyChar == (char)0) {
// The function timed out
} else {
// The user pressed a key
}发布于 2013-01-17 18:22:02
static ConsoleKeyInfo? MyReadKey()
{
var task = Task.Run(() => Console.ReadKey(true));
bool read = task.Wait(1000);
if (read) return task.Result;
return null;
}var key = MyReadKey();
if (key == null)
{
Console.WriteLine("NULL");
}
else
{
Console.WriteLine(key.Value.Key);
}发布于 2013-01-17 18:08:21
你是说像这样的事吗?
Console.WriteLine("Waiting for input for 10 seconds...");
DateTime start = DateTime.Now;
bool gotKey = false;
while ((DateTime.Now - start).TotalSeconds < 10)
{
if (Console.KeyAvailable)
{
gotKey = true;
break;
}
}
if (gotKey)
{
string s = Console.ReadLine();
}
else
Console.WriteLine("Timed out");https://stackoverflow.com/questions/14385044
复制相似问题