简体   繁体   English

ReadKey 在线程超时结束之前获取字符

[英]ReadKey getting characters pressed before a thread timeout has ended

i'm attempting my first c# console-based game.我正在尝试我的第一个 c# 基于控制台的游戏。 I created a centered credits intro with a "press any key to continue..." printed at the end.我创建了一个居中的学分介绍,最后印有“按任意键继续...”。 I used Console.ReadKey() to emulate a pause as it waits for user input.我使用Console.ReadKey()在等待用户输入时模拟暂停。 The problem is that you can 'stack' inputs, there is probably a better term but essentially, while the console is in a timeout the key inputs are still read and are queued until the timeout ends.问题是您可以“堆叠”输入,可能有一个更好的术语,但本质上,当控制台处于超时状态时,仍会读取关键输入并排队等待超时结束。 for example;例如;

//10 second wait
//this is where I would press a key
Thread.Sleep(10000);
char x = Console.ReadKey().KeyChar;
//x will be equal to whatever key I pressed before the timeout

this is not the functionality i'm after.这不是我想要的功能。 does anyone have a solution to this eg;有人对此有解决方案吗? not use Thread.Sleep() or Console.ReadKey()不使用Thread.Sleep()Console.ReadKey()

If you still do not understand the question, press a key while the Thread.Sleep() is still in effect and the readkey, after the time is up will print that character.如果您仍然不理解问题,请在Thread.Sleep()仍然有效并且 readkey 时按一个键,时间到后将打印该字符。 does anyone know how to stop the reading of the key?有谁知道如何停止读取密钥?

If you would like actual project code, just ask.如果您想要实际的项目代码,请询问。 Although I see it as irrelevant for this question.虽然我认为这与这个问题无关。

If you want to clear the buffer before waiting for a key, you can call Console.ReadKey(true) in a loop for as long as there is a KeyAvailable .如果要在等待密钥之前清除缓冲区,只要有KeyAvailable ,就可以在循环中调用Console.ReadKey(true) Passing true to the method specifies that the key should be intercepted and not be output to the console window.true传递给方法指定应该截取密钥,而不是 output 到控制台 window。

For example:例如:

Thread.Sleep(TimeSpan.FromSeconds(10));

// Clear buffer by "throwing away" any keys that were pressed while we were sleeping
while(Console.KeyAvailable) Console.ReadKey(true);

char x = Console.ReadKey().KeyChar;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM